INSTRUCTION
stringlengths 202
35.5k
| RESPONSE
stringlengths 75
161k
|
---|---|
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::CreateService < BaseServices::Create
private
def instance_class
Member
end
def after_perform(service_call)
return service_call unless service_call.success?
work_package_member = service_call.result
add_group_memberships(work_package_member)
send_notification(work_package_member)
service_call
end
def add_group_memberships(work_package_member)
return unless work_package_member.principal.is_a?(Group)
Groups::CreateInheritedRolesService
.new(work_package_member.principal,
current_user: user,
contract_class: EmptyContract)
.call(user_ids: work_package_member.principal.user_ids,
send_notifications: false,
project_ids: [work_package_member.project_id])
end
def send_notification(work_package_member)
OpenProject::Notifications.send(OpenProject::Events::WORK_PACKAGE_SHARED,
work_package_member:,
send_notifications: true)
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_create_service'
RSpec.describe WorkPackageMembers::CreateService, type: :model do
subject(:service_call) { instance.call(call_attributes) }
let(:instance) { described_class.new(user:) }
let(:user) { build_stubbed(:user) }
let(:richard) { build_stubbed(:user) }
let(:dinesh) { build_stubbed(:user) }
let(:gilfoyle) { build_stubbed(:user) }
let(:cool_group) do
build_stubbed(:group).tap do |group|
allow(group)
.to receive(:user_ids)
.and_return([dinesh.id, gilfoyle.id])
end
end
let(:role) { build_stubbed(:view_work_package_role) }
let(:work_package) { build_stubbed(:work_package) }
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
def stub_notifications
allow(OpenProject::Notifications)
.to receive(:send)
end
before { stub_notifications }
it_behaves_like 'BaseServices create service' do
let(:model_class) { Member }
let(:principal) { richard }
let(:call_attributes) { { principal:, roles: [role], entity: work_package, project: work_package.project } }
context 'when successful' do
it 'sends a notification' do
service_call
expect(OpenProject::Notifications)
.to have_received(:send)
.with(OpenProject::Events::WORK_PACKAGE_SHARED,
work_package_member: model_instance,
send_notifications: true)
end
context 'for a User' do
it 'does not create any inherited roles' do
service_call
expect(Groups::CreateInheritedRolesService)
.not_to have_received(:new)
end
end
context 'for a Group' do
let(:principal) { cool_group }
let(:model_instance) { build_stubbed(:member, principal:) }
it "generates the work package memberships and roles for the group's users" do
service_call
expect(Groups::CreateInheritedRolesService)
.to have_received(:new)
.with(principal,
current_user: user,
contract_class: EmptyContract)
expect(inherited_roles_service)
.to have_received(:call)
.with(user_ids: principal.user_ids,
project_ids: [model_instance.project_id],
send_notifications: false)
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::DeleteService < BaseServices::Delete
include Members::Concerns::CleanedUp
protected
def after_perform(service_call)
super(service_call).tap do |call|
work_package_member = call.result
cleanup_for_group(work_package_member)
end
end
def cleanup_for_group(work_package_member)
return unless work_package_member.principal.is_a?(Group)
Groups::CleanupInheritedRolesService
.new(work_package_member.principal, current_user: user, contract_class: EmptyContract)
.call
end
end
``` | # frozen_string_literal: true
# -- 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'
require 'services/base_services/behaves_like_delete_service'
RSpec.describe WorkPackageMembers::DeleteService, type: :model do
it_behaves_like 'BaseServices delete service' do
let(:model_class) { Member }
let(:model_instance) { build_stubbed(:work_package_member, principal:) }
let(:principal) { user }
let!(:cleanup_service_instance) do
instance_double(Members::CleanupService, call: nil).tap do |service_double|
allow(Members::CleanupService)
.to receive(:new)
.with(principal, model_instance.project_id)
.and_return(service_double)
end
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
context "when the model's principal is a group" do
let(:principal) { build_stubbed(:group) }
let!(:cleanup_inherited_roles_service_instance) do
instance_double(Groups::CleanupInheritedRolesService, call: nil).tap do |service_double|
allow(Groups::CleanupInheritedRolesService)
.to receive(:new)
.with(principal,
current_user: user,
contract_class: EmptyContract)
.and_return(service_double)
end
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) 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 creation of a local repository.
class SCM::CreateManagedRepositoryService < SCM::BaseRepositoryService
##
# Checks if a given repository may be created and managed locally.
# Registers an job to create the repository on disk.
#
# @return True if the repository creation request has been initiated, false otherwise.
def call
if repository.managed? && repository.manageable?
##
# We want to move this functionality in a Delayed Job,
# but this heavily interferes with the error handling of the whole
# repository management process.
# Instead, this will be refactored into a single service wrapper for
# creating and deleting repositories, which provides transactional DB access
# as well as filesystem access.
if repository.class.manages_remote?
SCM::CreateRemoteRepositoryJob.perform_now(repository)
else
SCM::CreateLocalRepositoryJob.ensure_not_existing!(repository)
SCM::CreateLocalRepositoryJob.perform_later(repository)
end
return true
end
false
rescue Errno::EACCES
@rejected = I18n.t('repositories.errors.path_permission_failed',
path: repository.root_url)
false
rescue SystemCallError => e
@rejected = I18n.t('repositories.errors.filesystem_access_failed',
message: e.message)
false
rescue OpenProject::SCM::Exceptions::SCMError => e
@rejected = e.message
false
end
##
# Returns the error symbol
def localized_rejected_reason
@rejected ||= I18n.t('repositories.errors.not_manageable')
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 SCM::CreateManagedRepositoryService, skip_if_command_unavailable: 'svnadmin' do
let(:user) { build(:user) }
let(:config) { {} }
let(:project) { build(:project) }
let(:repository) { build(:repository_subversion) }
subject(:service) { SCM::CreateManagedRepositoryService.new(repository) }
before do
allow(OpenProject::Configuration).to receive(:[]).and_call_original
allow(OpenProject::Configuration).to receive(:[]).with('scm').and_return(config)
end
shared_examples 'does not create a filesystem repository' do
it 'does not create a filesystem repository' do
expect(repository.managed?).to be false
expect(service.call).to be false
end
end
context 'with no managed configuration' do
it_behaves_like 'does not create a filesystem repository'
end
context 'with managed repository' do
# Must not .create a managed repository, or it will call this service itself!
let(:repository) do
repo = Repository::Subversion.new(scm_type: :managed)
repo.project = project
repo
end
context 'but no managed config' do
it 'does not create a filesystem repository' do
expect(repository.managed?).to be true
expect(service.call).to be false
end
end
end
context 'with managed local config' do
include_context 'with tmpdir'
let(:config) do
{
subversion: { manages: File.join(tmpdir, 'svn') },
git: { manages: File.join(tmpdir, 'git') }
}
end
let(:repository) do
repo = Repository::Subversion.new(scm_type: :managed)
repo.project = project
repo.configure(:managed, nil)
# Ignore default creation
allow(repo).to receive(:create_managed_repository)
repo.save!
repo
end
before do
allow_any_instance_of(SCM::CreateLocalRepositoryJob)
.to receive(:repository).and_return(repository)
allow_any_instance_of(SCM::CreateRemoteRepositoryJob)
.to receive(:repository).and_return(repository)
end
it 'creates the repository' do
expect(service.call).to be true
perform_enqueued_jobs
expect(File.directory?(repository.root_url)).to be true
end
context 'with pre-existing path on filesystem' do
before do
allow(File).to receive(:directory?).and_return(true)
end
it 'does not create the repository' do
expect(service.call).to be false
expect(service.localized_rejected_reason)
.to eq(I18n.t('repositories.errors.exists_on_filesystem'))
end
end
context 'with a permission error occurring in the Job' do
before do
allow(SCM::CreateLocalRepositoryJob)
.to receive(:new).and_raise(Errno::EACCES)
end
it 'returns the correct error' do
expect(service.call).to be false
expect(service.localized_rejected_reason)
.to eq(I18n.t('repositories.errors.path_permission_failed',
path: repository.root_url))
end
end
context 'with an OS error occurring in the Job' do
before do
allow(SCM::CreateLocalRepositoryJob)
.to receive(:new).and_raise(Errno::ENOENT)
end
it 'returns the correct error' do
expect(service.call).to be false
expect(service.localized_rejected_reason)
.to include('An error occurred while accessing the repository in the filesystem')
end
end
end
context 'with managed remote config', webmock: true do
let(:url) { 'http://myreposerver.example.com/api/' }
let(:config) do
{
subversion: { manages: url }
}
end
let(:repository) do
repo = build(:repository_subversion, scm_type: :managed)
repo.project = project
repo.configure(:managed, nil)
repo
end
it 'detects the remote config' do
expect(repository.class.managed_remote.to_s).to eq(url)
expect(repository.class).to be_manages_remote
end
context 'with a remote callback' do
let(:returned_url) { 'file:///tmp/some/url/to/repo' }
let(:root_url) { '/tmp/some/url/to/repo' }
before do
stub_request(:post, url)
.to_return(
status: 200,
body: { url: returned_url, path: root_url }.to_json
)
end
shared_examples 'calls the callback' do
before do
# Avoid setting up a second call to the remote during save
# since we only templated the repository, not created one!
expect(repository).to receive(:save).and_return(true)
end
it do
expect(SCM::CreateRemoteRepositoryJob)
.to receive(:new).and_call_original
expect(service.call).to be true
expect(repository.root_url).to eq(root_url)
expect(repository.url).to eq(returned_url)
expect(WebMock)
.to have_requested(:post, url)
.with(body: hash_including(action: 'create'))
end
end
context 'with http' do
it_behaves_like 'calls the callback'
end
context 'with https' do
let(:url) { 'https://myreposerver.example.com/api/' }
let(:config) do
{
subversion: { manages: url, insecure: }
}
end
let(:instance) { SCM::CreateRemoteRepositoryJob.new }
let(:job_call) { instance.perform(repository) }
context 'with insecure option' do
let(:insecure) { true }
it_behaves_like 'calls the callback'
it 'uses the insecure option' do
job_call
expect(instance.send(:configured_verification)).to eq(OpenSSL::SSL::VERIFY_NONE)
end
end
context 'without insecure option' do
let(:insecure) { false }
it 'uses the insecure option' do
job_call
expect(instance.send(:configured_verification)).to eq(OpenSSL::SSL::VERIFY_PEER)
end
end
end
end
context 'with a faulty remote callback' do
before do
stub_request(:post, url)
.to_return(status: 400, body: { success: false, message: 'An error occurred' }.to_json)
end
it 'calls the callback' do
expect(SCM::CreateRemoteRepositoryJob)
.to receive(:new).and_call_original
expect(service.call).to be false
expect(service.localized_rejected_reason)
.to eq("Calling the managed remote failed with message 'An error occurred' (Code: 400)")
expect(WebMock)
.to have_requested(:post, url)
.with(body: hash_including(action: 'create'))
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 a repository service for building checkout instructions if supported
class SCM::CheckoutInstructionsService
attr_reader :repository, :user, :path
def initialize(repository, path: nil, user: User.current)
@repository = repository
@user = user
@path = path
end
##
# Retrieve the checkout URL using the repository vendor information
# It may additionally set a path parameter, if the repository supports subtree checkout
def checkout_url(with_path = false)
repository.scm.checkout_url(repository,
checkout_base_url,
with_path ? URI.encode_www_form_component(@path) : nil)
end
##
# Returns the checkout command from SCM adapter
# (e.g., `git clone`)
def checkout_command
repository.scm.checkout_command
end
##
# Returns the checkout base URL as defined in settings.
def checkout_base_url
checkout_settings['base_url']
end
##
# Returns the instructions defined in the settings.
def instructions
checkout_settings['text'].presence ||
I18n.t("repositories.checkout.default_instructions.#{repository.vendor}")
end
##
# Returns true when the checkout URL may target a subtree of the repository.
def subtree_checkout?
repository.scm.subtree_checkout?
end
##
# Determines whether the checkout URL may be built, i.e. all information is available
# This is the case when the base_url is set or the vendor doesn't use base URLs.
def checkout_url_buildable?
!repository.class.requires_checkout_base_url? || checkout_base_url.present?
end
##
# Returns whether the repository supports showing checkout information
# and has been configured for it.
def available?
checkout_enabled? &&
repository.supports_checkout_info? &&
checkout_url_buildable?
end
def checkout_enabled?
checkout_settings['enabled'].to_i > 0
end
def supported_but_not_enabled?
repository.supports_checkout_info? && !checkout_enabled?
end
##
# Determines whether permissions for the given repository
# are available.
def manages_permissions?
repository.managed?
end
##
# Returns one of the following permission symbols for the given user
#
# - :readwrite: When user is allowed to read and commit (:commit_access)
# - :read: When user is allowed to checkout the repository, but not commit (:browse_repository)
# - :none: Otherwise
#
# Note that this information is only applicable when the repository is managed,
# because otherwise OpenProject does not control the repository permissions.
# Use +manages_permissions?+ to check whether this is the case.
#
def permission
project = repository.project
if user.allowed_in_project?(:commit_access, project)
:readwrite
elsif user.allowed_in_project?(:browse_repository, project)
:read
else
:none
end
end
##
# Returns whether the given user may checkout the repository
#
# Note that this information is only applicable when the repository is managed,
# because otherwise OpenProject does not control the repository permissions.
# Use +manages_permissions?+ to check whether this is the case.
def may_checkout?
%i[readwrite read].include?(permission)
end
##
# Returns whether the given user may commit to the repository
#
# Note that this information is only applicable when the repository is managed,
# because otherwise OpenProject does not control the repository permissions.
# Use +manages_permissions?+ to check whether this is the case.
def may_commit?
permission == :readwrite
end
private
def checkout_settings
@settings ||= begin
hash = Setting.repository_checkout_data[repository.vendor.to_s]
hash.presence || {}
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 SCM::CheckoutInstructionsService do
let(:user) { build(:user) }
let(:project) { build(:project) }
let(:url) { 'file:///tmp/some/svn/repo' }
let(:repository) do
build(:repository_subversion,
url:,
project:)
end
let(:base_url) { 'http://example.org/svn/' }
let(:path) { nil }
let(:text) { 'foo' }
let(:checkout_hash) do
{
'git' => { 'enabled' => '0' },
'subversion' => { 'enabled' => '1',
'text' => text,
'base_url' => base_url }
}
end
subject(:service) { SCM::CheckoutInstructionsService.new(repository, user:, path:) }
before do
allow(Setting).to receive(:repository_checkout_data).and_return(checkout_hash)
end
describe '#checkout_url' do
shared_examples 'builds the correct URL' do
it 'builds the correct URL' do
expect(service.checkout_url)
.to eq(URI("http://example.org/svn/#{project.identifier}"))
end
shared_examples 'valid checkout URL' do
it do
expect(service.checkout_url(path))
.to eq(URI("http://example.org/svn/#{project.identifier}/#{expected_path}"))
end
end
it_behaves_like 'valid checkout URL' do
let(:path) { 'foo/bar' }
let(:expected_path) { path }
end
it_behaves_like 'valid checkout URL' do
let(:path) { 'foo/bar with spaces' }
let(:expected_path) { 'foo/bar%20with%20spaces' }
end
it_behaves_like 'valid checkout URL' do
let(:path) { 'foo/bar with §\"!??```' }
let(:expected_path) { 'foo/%C2%A7%22!??%60%60%60' }
end
end
end
describe '#checkout_command' do
it 'returns the SCM vendor command' do
expect(service.checkout_command).to eq('svn checkout')
end
end
describe '#instructions' do
it 'returns the setting when defined' do
expect(service.instructions).to eq('foo')
end
context 'no setting defined' do
let(:text) { nil }
it 'returns the default translated instructions' do
expect(service.instructions)
.to eq(I18n.t('repositories.checkout.default_instructions.subversion'))
end
end
end
describe '#settings' do
it 'svn is available for checkout' do
expect(service.available?).to be true
expect(service.checkout_enabled?).to be true
end
it 'has the correct settings' do
expect(Setting.repository_checkout_data['subversion']['enabled']).to eq('1')
expect(service.instructions).to eq('foo')
expect(service.checkout_base_url).to eq(base_url)
end
context 'missing checkout base URL' do
let(:base_url) { '' }
it 'is not available for checkout even when enabled' do
expect(service.checkout_base_url).to eq(base_url)
expect(service.checkout_enabled?).to be true
expect(service.available?).to be false
end
end
context 'disabled repository' do
let(:repository) { build(:repository_git) }
it 'git is not available for checkout' do
expect(service.available?).to be false
expect(service.checkout_enabled?).to be false
end
end
end
describe '#permission' do
context 'with no managed repository' do
it 'is not applicable' do
expect(service.manages_permissions?).to be false
end
end
context 'with managed repository' do
before do
allow(repository).to receive(:managed?).and_return(true)
end
it 'is applicable' do
expect(service.manages_permissions?).to be true
end
it 'returns readwrite permission when user has commit_access permission' do
mock_permissions_for(user) do |mock|
mock.allow_in_project :commit_access, project:
end
expect(service.permission).to eq(:readwrite)
end
it 'returns read permission when user has browse_repository permission' do
mock_permissions_for(user) do |mock|
mock.allow_in_project :browse_repository, project:
end
expect(service.permission).to eq(:read)
end
it 'returns none permission when user has no permission' do
mock_permissions_for(user, &:forbid_everything)
expect(service.permission).to eq(:none)
end
it 'returns the correct permissions for commit access' do
mock_permissions_for(user) do |mock|
mock.allow_in_project :commit_access, project:
end
expect(service.may_commit?).to be true
expect(service.may_checkout?).to be true
end
it 'returns the correct permissions for read access' do
mock_permissions_for(user) do |mock|
mock.allow_in_project :browse_repository, project:
end
expect(service.may_commit?).to be false
expect(service.may_checkout?).to be true
end
it 'returns the correct permissions for no access' do
mock_permissions_for(user, &:forbid_everything)
expect(service.may_commit?).to be false
expect(service.may_checkout?).to be false
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 a repository factory for building temporary and permanent repositories.
class SCM::RepositoryFactoryService
attr_reader :project, :params, :repository
def initialize(project, params)
@project = project
@params = params
end
##
# Build a full repository from a given scm_type
# and persists it.
#
# @return [Boolean] true iff the repository was built
def build_and_save
build_guarded do
repository = build_with_type(params.fetch(:scm_type).to_sym)
if repository.save
repository
else
raise OpenProject::SCM::Exceptions::RepositoryBuildError.new(
repository.errors.full_messages.join("\n")
)
end
end
end
##
# Build a temporary repository used only for determining available settings and types
# of that particular vendor.
#
# @return [Boolean] true iff the repository was built
def build_temporary
build_guarded do
build_with_type(nil)
end
end
def build_error
I18n.t('repositories.errors.build_failed', reason: @build_failed_msg)
end
private
##
# Helper to actually build the repository and return it.
# May raise +OpenProject::SCM::Exceptions::RepositoryBuildError+ internally.
#
# @param [Symbol] scm_type Type to build the repository with. May be nil
# during temporary build
def build_with_type(scm_type)
Repository.build(
project,
params.fetch(:scm_vendor).to_sym,
params.fetch(:repository, {}),
scm_type
)
end
def build_guarded
@repository = yield
@repository.present?
rescue OpenProject::SCM::Exceptions::RepositoryBuildError => e
@build_failed_msg = e.message
nil
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 SCM::RepositoryFactoryService do
let(:user) { build(:user) }
let(:project) { build(:project) }
let(:enabled_scms) { ['subversion', 'git'] }
let(:params_hash) { {} }
let(:params) { ActionController::Parameters.new params_hash }
subject(:service) { SCM::RepositoryFactoryService.new(project, params) }
before do
allow(Setting).to receive(:enabled_scm).and_return(enabled_scms)
end
context 'with empty hash' do
it 'does not build a repository' do
expect { service.build_temporary }
.to raise_error KeyError
expect(service.repository).to be_nil
end
end
context 'with valid vendor' do
let(:params_hash) do
{ scm_vendor: 'subversion' }
end
it 'allows temporary build repository' do
expect(service.build_temporary).to be true
expect(service.repository).not_to be_nil
end
it 'does not allow to persist a repository' do
expect { service.build_and_save }
.to raise_error(ActionController::ParameterMissing)
expect(service.repository).to be_nil
end
end
context 'with invalid vendor' do
let(:params_hash) do
{ scm_vendor: 'not_subversion', scm_type: 'foo' }
end
it 'does not allow to temporary build repository' do
expect { service.build_temporary }.not_to raise_error
expect(service.repository).to be_nil
expect(service.build_error).to include('The SCM vendor not_subversion is disabled')
end
it 'does not allow to persist a repository' do
expect { service.build_temporary }.not_to raise_error
expect(service.repository).to be_nil
expect(service.build_error).to include('The SCM vendor not_subversion is disabled')
end
end
context 'with vendor and type' do
let(:params_hash) do
{ scm_vendor: 'subversion', scm_type: 'existing' }
end
it 'does not allow to persist a repository without URL' do
expect(service.build_and_save).not_to be true
expect(service.repository).to be_nil
expect(service.build_error).to include("URL can't be blank")
end
end
context 'with invalid hash' do
let(:params_hash) do
{
scm_vendor: 'subversion', scm_type: 'existing',
repository: { url: '/tmp/foo.svn' }
}
end
it 'does not allow to persist a repository URL' do
expect(service.build_and_save).not_to be true
expect(service.repository).to be_nil
expect(service.build_error).to include('URL is invalid')
end
end
context 'with valid hash' do
let(:params_hash) do
{
scm_vendor: 'subversion', scm_type: 'existing',
repository: { url: 'file:///tmp/foo.svn' }
}
end
it 'allows to persist a repository without URL' do
expect(service.build_and_save).to be true
expect(service.repository).to be_a(Repository::Subversion)
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 asynchronous deletion of a local repository.
class SCM::DeleteManagedRepositoryService < SCM::BaseRepositoryService
##
# Checks if a given repository may be deleted
# Registers an asynchronous job to delete the repository on disk.
#
def call
return false unless repository.managed?
if repository.class.manages_remote?
SCM::DeleteRemoteRepositoryJob.perform_now(repository)
true
else
delete_local_repository
end
rescue OpenProject::SCM::Exceptions::SCMError => e
@rejected = e.message
false
end
def delete_local_repository
# Create necessary changes to repository to mark
# it as managed by OP, but delete asynchronously.
managed_path = repository.root_url
if File.directory?(managed_path)
##
# We want to move this functionality in a Delayed Job,
# but this heavily interferes with the error handling of the whole
# repository management process.
# Instead, this will be refactored into a single service wrapper for
# creating and deleting repositories, which provides transactional DB access
# as well as filesystem access.
SCM::DeleteLocalRepositoryJob.perform_now(managed_path)
end
true
rescue SystemCallError => e
@rejected = I18n.t('repositories.errors.managed_delete_local',
path: repository.root_url,
error_message: e.message)
false
end
##
# Returns the error symbol
def localized_rejected_reason
@rejected ||= I18n.t('repositories.errors.managed_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'
RSpec.describe SCM::DeleteManagedRepositoryService, skip_if_command_unavailable: 'svnadmin' do
let(:user) { build(:user) }
let(:config) { {} }
let(:project) { build(:project) }
let(:repository) { build(:repository_subversion) }
subject(:service) { SCM::DeleteManagedRepositoryService.new(repository) }
before do
allow(OpenProject::Configuration).to receive(:[]).and_call_original
allow(OpenProject::Configuration).to receive(:[]).with('scm').and_return(config)
allow(Setting).to receive(:enabled_scm).and_return(['subversion', 'git'])
end
shared_examples 'does not delete the repository' do
it 'does not delete the repository' do
expect(repository.managed?).to be false
expect(service.call).to be false
end
end
context 'with no managed configuration' do
it_behaves_like 'does not delete the repository'
end
context 'with managed repository, but no config' do
let(:repository) { build(:repository_subversion, scm_type: :managed) }
it 'does allow to delete the repository' do
expect(repository.managed?).to be true
expect(service.call).to be true
end
end
context 'with managed repository and managed config' do
include_context 'with tmpdir'
let(:config) do
{
subversion: { manages: File.join(tmpdir, 'svn') },
git: { manages: File.join(tmpdir, 'git') }
}
end
let(:repository) do
repo = Repository::Subversion.new(scm_type: :managed)
repo.project = project
repo.configure(:managed, nil)
repo.save!
perform_enqueued_jobs
repo
end
it 'deletes the repository' do
expect(File.directory?(repository.root_url)).to be true
expect(service.call).to be true
expect(File.directory?(repository.root_url)).to be false
end
it 'does not raise an exception upon permission errors' do
expect(File.directory?(repository.root_url)).to be true
expect(SCM::DeleteLocalRepositoryJob)
.to receive(:new).and_raise(Errno::EACCES)
expect(service.call).to be false
end
context 'and parent project' do
let(:parent) { create(:project) }
let(:project) { create(:project, parent:) }
let(:repo_path) do
Pathname.new(File.join(tmpdir, 'svn', project.identifier))
end
it 'does not delete anything but the repository itself' do
expect(service.call).to be true
path = Pathname.new(repository.root_url)
expect(path).to eq(repo_path)
expect(path.exist?).to be false
expect(path.parent.exist?).to be true
expect(path.parent.to_s).to eq(repository.class.managed_root)
end
end
end
context 'with managed remote config', webmock: true do
let(:url) { 'http://myreposerver.example.com/api/' }
let(:config) do
{
subversion: { manages: url }
}
end
let(:repository) do
repo = Repository::Subversion.new(scm_type: :managed)
repo.project = project
repo.configure(:managed, nil)
repo
end
context 'with a valid remote' do
before do
stub_request(:post, url).to_return(status: 200, body: {}.to_json)
end
it 'calls the callback' do
expect(SCM::DeleteRemoteRepositoryJob)
.to receive(:perform_now)
.and_call_original
expect(service.call).to be true
expect(WebMock)
.to have_requested(:post, url)
.with(body: hash_including(identifier: repository.repository_identifier,
action: 'delete'))
end
end
context 'with a remote callback returning an error' do
before do
stub_request(:post, url)
.to_return(status: 400, body: { success: false, message: 'An error occurred' }.to_json)
end
it 'calls the callback' do
expect(SCM::DeleteRemoteRepositoryJob)
.to receive(:perform_now)
.and_call_original
expect(service.call).to be false
expect(service.localized_rejected_reason)
.to eq("Calling the managed remote failed with message 'An error occurred' (Code: 400)")
expect(WebMock)
.to have_requested(:post, url)
.with(body: hash_including(action: 'delete'))
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 Authorization::EnterpriseService
attr_accessor :token
GUARDED_ACTIONS = %i(
baseline_comparison
board_view
conditional_highlighting
custom_actions
custom_fields_in_projects_list
date_alerts
define_custom_style
edit_attribute_groups
grid_widget_wp_graph
ldap_groups
openid_providers
placeholder_users
readonly_work_packages
team_planner_view
two_factor_authentication
work_package_query_relation_columns
work_package_sharing
).freeze
def initialize(token)
self.token = token
end
# Return a true ServiceResult if the token contains this particular action.
def call(action)
allowed =
if token.nil? || token.token_object.nil? || token.expired?
false
else
process(action)
end
result(allowed)
end
private
def process(action)
# Every non-expired token
GUARDED_ACTIONS.include?(action.to_sym)
end
def result(bool)
ServiceResult.new(success: bool, result: bool)
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::EnterpriseService do
let(:token_object) do
token = OpenProject::Token.new
token.subscriber = 'Foobar'
token.mail = '[email protected]'
token.starts_at = Date.today
token.expires_at = nil
token
end
let(:token) { double('EnterpriseToken', token_object:) }
let(:instance) { described_class.new(token) }
let(:result) { instance.call(action) }
let(:action) { :an_action }
describe '#initialize' do
it 'has the token' do
expect(instance.token).to eql token
end
end
describe 'expiry' do
before do
allow(token).to receive(:expired?).and_return(expired)
end
context 'when expired' do
let(:expired) { true }
it 'returns a false result' do
expect(result).to be_a ServiceResult
expect(result.result).to be_falsey
expect(result.success?).to be_falsey
end
end
context 'when active' do
let(:expired) { false }
context 'invalid action' do
it 'returns false' do
expect(result.result).to be_falsey
end
end
%i(baseline_comparison
board_view
conditional_highlighting
custom_actions
custom_fields_in_projects_list
date_alerts
define_custom_style
edit_attribute_groups
grid_widget_wp_graph
ldap_groups
openid_providers
placeholder_users
readonly_work_packages
team_planner_view
two_factor_authentication
work_package_query_relation_columns
work_package_sharing).each do |guarded_action|
context "guarded action #{guarded_action}" do
let(:action) { guarded_action }
it 'returns a true result' do
expect(result).to be_a ServiceResult
expect(result.result).to be_truthy
expect(result.success?).to be_truthy
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 Authorization::QueryTransformation
attr_accessor :on, :name, :after, :before, :block
def initialize(on,
name,
after,
before,
block)
self.on = on
self.name = name
self.after = after
self.before = before
self.block = block
end
def apply(*args)
block.call(*args)
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::QueryTransformation do
let(:on) { 'on' }
let(:name) { 'name' }
let(:after) { 'after' }
let(:before) { 'before' }
let(:block) { ->(*args) { args } }
let(:instance) do
described_class.new on,
name,
after,
before,
block
end
context 'initialSetup' do
it 'sets on' do
expect(instance.on).to eql on
end
it 'sets name' do
expect(instance.name).to eql name
end
it 'sets after' do
expect(instance.after).to eql after
end
it 'sets before' do
expect(instance.before).to eql before
end
it 'sets block' do
expect(instance.block).to eql block
end
end
context 'apply' do
it 'calls the block' do
expect(instance.apply(1, 2, 3)).to match_array [1, 2, 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.
#++
class Authorization::UserProjectRolesQuery < Authorization::UserRolesQuery
transformations.register :all, :project_where_projection do |statement, user, _|
statement.where(users_table[:id].eq(user.id))
end
transformations.register users_members_join, :project_id_limit do |statement, _, project|
statement
.and(members_table[:project_id].eq(project.id))
.and(members_table[:entity_type].eq(nil))
.and(members_table[:entity_id].eq(nil))
end
transformations.register roles_member_roles_join, :builtin_role do |statement, user, project|
if project.public?
builtin_role = if user.logged?
Role::BUILTIN_NON_MEMBER
else
Role::BUILTIN_ANONYMOUS
end
builtin_role_condition = members_table[:id]
.eq(nil)
.and(roles_table[:builtin]
.eq(builtin_role))
statement = statement.or(builtin_role_condition)
end
statement
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::UserProjectRolesQuery do
let(:user) { build(:user) }
let(:anonymous) { build(:anonymous) }
let(:project) { build(:project, public: false) }
let(:project2) { build(:project, public: false) }
let(:public_project) { build(:project, public: true) }
let(:work_package) { build(:work_package, project:) }
let(:role) { build(:project_role) }
let(:role2) { build(:project_role) }
let(:wp_role) { build(:work_package_role) }
let(:anonymous_role) { build(:anonymous_role) }
let(:non_member) { build(:non_member) }
let(:member) { build(:member, project:, roles: [role], principal: user) }
let(:member2) { build(:member, project: project2, roles: [role2], principal: user) }
let(:wp_member) { build(:member, project:, roles: [wp_role], principal: user, entity: work_package) }
describe '.query' do
before do
non_member.save!
anonymous_role.save!
user.save!
end
it 'is a user relation' do
expect(described_class.query(user, project)).to be_a ActiveRecord::Relation
end
context 'with the user being a member in the project' do
before do
member.save!
end
it 'is the project roles' do
expect(described_class.query(user, project)).to match [role]
end
end
context 'without the user being member in the project' do
context 'with the project being private' do
it 'is empty' do
expect(described_class.query(user, project)).to be_empty
end
end
context 'with the project being public' do
it 'is the non member role' do
expect(described_class.query(user, public_project)).to contain_exactly(non_member)
end
end
end
context 'with the user being anonymous' do
context 'with the project being public' do
it 'is empty' do
expect(described_class.query(anonymous, public_project)).to contain_exactly(anonymous_role)
end
end
context 'without the project being public' do
it 'is empty' do
expect(described_class.query(anonymous, project)).to be_empty
end
end
end
context 'with the user being a member in two projects' do
before do
member.save!
member2.save!
end
it 'returns only the roles from the requested project' do
expect(described_class.query(user, project)).to contain_exactly(role)
end
end
context 'with the user being a member of a work package of the project' do
before { wp_member.save! }
context 'and not being a member of the project itself' do
it { expect(described_class.query(user, project)).to be_empty }
end
context 'and being a member of the project as well' do
before { member.save! }
it { expect(described_class.query(user, project)).to contain_exactly(role) }
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 Authorization::UserAllowedQuery < Authorization::AbstractUserQuery
self.model = User
transformations.register :all,
:member_roles_join do |statement|
statement.outer_join(member_roles_table)
.on(members_member_roles_join)
end
transformations.register :all,
:where_projection do |statement, action, project|
statement = statement.group(users_table[:id])
# No action allowed on archived projects
# No action allowed on disabled modules
if project.active? && project.allows_to?(action)
has_role = roles_table[:id].not_eq(nil)
has_permission = role_permissions_table[:id].not_eq(nil)
has_role_and_permission = if OpenProject::AccessControl.permission(action).public?
has_role
else
has_role.and(has_permission)
end
is_admin = if OpenProject::AccessControl.grant_to_admin?(action)
users_table[:admin].eq(true)
else
Arel::Nodes::Equality.new(1, 0)
end
statement.where(has_role_and_permission.or(is_admin))
else
statement.where(Arel::Nodes::Equality.new(1, 0))
end
end
transformations.register users_members_join,
:project_id_limit do |statement, _, project|
statement.and(members_table[:project_id].eq(project.id))
end
transformations.register :all,
:roles_join,
after: [:member_roles_join] do |statement, _, project|
statement.outer_join(roles_table)
.on(roles_member_roles_join(project))
end
transformations.register :all,
:role_permissions_join,
after: [:roles_join] do |statement, action|
if OpenProject::AccessControl.permission(action).public?
statement
else
statement.outer_join(role_permissions_table)
.on(roles_table[:id]
.eq(role_permissions_table[:role_id])
.and(role_permissions_table[:permission].eq(action.to_s)))
end
end
def self.roles_member_roles_join(project)
id_equal = roles_table[:id].eq(member_roles_table[:role_id])
if project.public?
member_or_public_project_condition(id_equal)
else
id_equal
end
end
def self.no_membership_and_non_member_role_condition
roles_table
.grouping(member_roles_table[:role_id]
.eq(nil)
.and(roles_table[:builtin].eq(Role::BUILTIN_NON_MEMBER)))
end
def self.anonymous_user_condition
users_table[:type]
.eq('AnonymousUser')
.and(roles_table[:builtin].eq(Role::BUILTIN_ANONYMOUS))
end
def self.member_or_public_project_condition(id_equal)
roles_table
.grouping(users_table[:type]
.eq('User')
.and(id_equal.or(no_membership_and_non_member_role_condition)))
.or(anonymous_user_condition)
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::UserAllowedQuery do
describe '.query' do
let(:user) { member.principal }
let(:anonymous) { build(:anonymous) }
let(:project) { build(:project, public: false) }
let(:project2) { build(:project, public: false) }
let(:role) { build(:project_role) }
let(:role2) { build(:project_role) }
let(:anonymous_role) { build(:anonymous_role) }
let(:non_member_role) { build(:non_member) }
let(:member) do
build(:member, project:,
roles: [role])
end
let(:action) { :view_work_packages }
let(:other_action) { :another }
let(:public_action) { :view_project }
before do
user.save!
anonymous.save!
anonymous_role.save!
non_member_role.save!
end
it 'is an AR relation' do
expect(described_class.query(action, project)).to be_a ActiveRecord::Relation
end
context 'w/o the project being public
w/ the user being member in the project
w/ the role having the necessary permission' do
before do
role.add_permission! action
role.save!
member.save!
end
it 'returns the user' do
expect(described_class.query(action, project)).to match_array [user]
end
end
context 'w/o the project being public
w/o the user being member in the project
w/ the user being admin' do
before do
user.update_attribute(:admin, true)
end
it 'returns the user' do
expect(described_class.query(action, project)).to match_array [user]
end
end
context 'w/o the project being public
w/ the user being member in the project
w/o the role having the necessary permission' do
before do
role.save!
member.save!
end
it 'is empty' do
expect(described_class.query(action, project)).to be_empty
end
end
context 'w/o the project being public
w/o the user being member in the project
w/ the role having the necessary permission' do
before do
role.add_permission! action
role.save!
end
it 'returns the user' do
expect(described_class.query(action, project)).to be_empty
end
end
context 'w/o the project being public
w/o the user being member in the project
w/ the user being member in a different project
w/ the role having the permission' do
before do
role.add_permission! action
role.save!
member.project = project2
member.save!
end
it 'is empty' do
expect(described_class.query(action, project)).to be_empty
end
end
context 'w/ the project being public
w/o the user being member in the project
w/ the user being member in a different project
w/ the role having the permission' do
before do
role.add_permission! action
role.save!
project.public = true
project.save!
member.project = project2
member.save!
end
it 'is empty' do
expect(described_class.query(action, project)).to be_empty
end
end
context 'w/ the project being public
w/o the user being member in the project
w/ the non member role having the necessary permission' do
before do
project.public = true
non_member = ProjectRole.non_member
non_member.add_permission! action
non_member.save
project.save!
end
it 'returns the user' do
expect(described_class.query(action, project)).to match_array [user]
end
end
context 'w/ the project being public
w/o the user being member in the project
w/ the anonymous role having the necessary permission' do
before do
project.public = true
anonymous_role = ProjectRole.anonymous
anonymous_role.add_permission! action
anonymous_role.save
project.save!
end
it 'returns the anonymous user' do
expect(described_class.query(action, project)).to match_array([anonymous])
end
end
context 'w/ the project being public
w/o the user being member in the project
w/ the non member role having another permission' do
before do
project.public = true
non_member = ProjectRole.non_member
non_member.add_permission! other_action
non_member.save
project.save!
end
it 'is empty' do
expect(described_class.query(action, project)).to be_empty
end
end
context 'w/ the project being private
w/o the user being member in the project
w/ the non member role having the permission' do
before do
non_member = ProjectRole.non_member
non_member.add_permission! action
non_member.save
project.save!
end
it 'is empty' do
expect(described_class.query(action, project)).to be_empty
end
end
context 'w/ the project being public
w/ the user being member in the project
w/o the role having the necessary permission
w/ the non member role having the permission' do
before do
project.public = true
project.save
role.add_permission! other_action
member.save!
non_member = ProjectRole.non_member
non_member.add_permission! action
non_member.save
end
it 'is empty' do
expect(described_class.query(action, project)).to be_empty
end
end
context 'w/o the project being public
w/ the user being member in the project
w/o the role having the permission
w/ the permission being public' do
before do
member.save!
end
it 'returns the user' do
expect(described_class.query(public_action, project)).to match_array [user]
end
end
context 'w/ the project being public
w/o the user being member in the project
w/o the role having the permission
w/ the permission being public' do
before do
project.public = true
project.save
end
it 'returns the user and anonymous' do
expect(described_class.query(public_action, project)).to match_array [user, anonymous]
end
end
context 'w/ the user being member in the project
w/ asking for a certain permission
w/ the permission belonging to a module
w/o the module being active' do
let(:permission) do
OpenProject::AccessControl.permissions.find { |p| p.project_module.present? }
end
before do
project.enabled_module_names = []
role.add_permission! permission.name
member.save!
end
it 'is empty' do
expect(described_class.query(permission.name, project)).to eq []
end
end
context 'w/ the user being member in the project
w/ asking for a certain permission
w/ the permission belonging to a module
w/ the module being active' do
let(:permission) do
OpenProject::AccessControl.permissions.find { |p| p.project_module.present? }
end
before do
project.enabled_module_names = [permission.project_module]
role.add_permission! permission.name
member.save!
end
it 'returns the user' do
expect(described_class.query(permission.name, project)).to eq [user]
end
end
context 'w/ the user being member in the project
w/ asking for a certain permission
w/ the user having the permission in the project
w/o the project being active' do
before do
role.add_permission! action
member.save!
project.update(active: false)
end
it 'is empty' do
expect(described_class.query(action, project)).to eq []
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 Authorization::QueryTransformations
def for?(on)
!!transformations[transformation_key(on)]
end
def for(on)
transformations[transformation_key(on)]
end
def register(on,
name,
after: [],
before: [],
&block)
transformation = ::Authorization::QueryTransformation.new(on, name, after, before, block)
add_transformation(transformation)
sort_transformations(on)
end
def copy
the_new = self.class.new
the_new.transformations = transformations.deep_dup
the_new.transformation_order = transformation_order.deep_dup
the_new
end
protected
attr_accessor :transformations,
:transformation_order
private
def transformation_key(on)
if on.respond_to?(:to_sql)
on.to_sql
else
on
end
end
def transformations
@transformations ||= {}
end
def transformation_order
@transformation_order ||= ::Authorization::QueryTransformationsOrder.new
end
def add_transformation(transformation)
transformations[transformation_key(transformation.on)] ||= []
transformations[transformation_key(transformation.on)] << transformation
transformation_order << transformation
end
def sort_transformations(on)
desired_order = transformation_order.full_order
transformations[transformation_key(on)].sort_by! { |x| desired_order.index x.name }
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::QueryTransformations do
let(:instance) { described_class.new }
context 'registering a transformation' do
before do
instance.register(:on, :name) do |*args|
args
end
end
describe '#for?' do
it 'is true for the registered name' do
expect(instance.for?(:on)).to be_truthy
end
it 'is false for another name' do
expect(instance.for?(:other_name)).to be_falsey
end
end
describe '#for' do
it 'returns an array of transformations for the registered name' do
expect(instance.for(:on).length).to be 1
expect(instance.for(:on)[0].on).to be :on
expect(instance.for(:on)[0].name).to be :name
expect(instance.for(:on)[0].block.call(1, 2, 3)).to match_array [1, 2, 3]
end
it 'is nil for another name' do
expect(instance.for(:other_name)).to be_nil
end
end
end
context 'registering two transformations depending via after' do
before do
instance.register(:on, :transformation1, after: [:transformation2]) do |*args|
args
end
instance.register(:on, :transformation2) do |*args|
args.join(', ')
end
end
describe '#for?' do
it 'is true for the registered name' do
expect(instance.for?(:on)).to be_truthy
end
it 'is false for another name' do
expect(instance.for?(:other_name)).to be_falsey
end
end
describe '#for' do
it 'returns an array of transformations for the registered name' do
expect(instance.for(:on).length).to be 2
expect(instance.for(:on)[0].on).to be :on
expect(instance.for(:on)[0].name).to be :transformation2
expect(instance.for(:on)[0].block.call(1, 2, 3)).to eql '1, 2, 3'
expect(instance.for(:on)[1].on).to be :on
expect(instance.for(:on)[1].name).to be :transformation1
expect(instance.for(:on)[1].block.call(1, 2, 3)).to match_array [1, 2, 3]
end
end
end
context 'registering two transformations depending via before' do
before do
instance.register(:on, :transformation1) do |*args|
args
end
instance.register(:on, :transformation2, before: [:transformation1]) do |*args|
args.join(', ')
end
end
describe '#for?' do
it 'is true for the registered name' do
expect(instance.for?(:on)).to be_truthy
end
it 'is false for another name' do
expect(instance.for?(:other_name)).to be_falsey
end
end
describe '#for' do
it 'returns an array of transformations for the registered name' do
expect(instance.for(:on).length).to be 2
expect(instance.for(:on)[0].on).to be :on
expect(instance.for(:on)[0].name).to be :transformation2
expect(instance.for(:on)[0].block.call(1, 2, 3)).to eql '1, 2, 3'
expect(instance.for(:on)[1].on).to be :on
expect(instance.for(:on)[1].name).to be :transformation1
expect(instance.for(:on)[1].block.call(1, 2, 3)).to match_array [1, 2, 3]
end
end
end
context 'registering two mutually dependent transformations' do
it 'fails' do
instance.register(:on, :transformation1, before: [:transformation2]) do |*args|
args
end
expected_order = %i[transformation1 transformation2]
expect do
instance.register(:on, :transformation2, before: [:transformation1]) do |*args|
args.join(', ')
end
end.to raise_error "Cannot sort #{expected_order} into the list of transformations"
end
end
end
|
Write RSpec test file for following ruby class
```ruby
module Authorization
class UserPermissibleService
attr_accessor :user
def initialize(user)
@user = user
end
def allowed_globally?(permission)
perms = contextual_permissions(permission, :global)
return false unless authorizable_user?
return true if admin_and_all_granted_to_admin?(perms)
cached_permissions(nil).intersect?(perms.map(&:name))
end
def allowed_in_project?(permission, projects_to_check)
perms = contextual_permissions(permission, :project)
return false if projects_to_check.blank?
return false unless authorizable_user?
projects = Array(projects_to_check)
projects.all? do |project|
allowed_in_single_project?(perms, project)
end
end
def allowed_in_any_project?(permission)
perms = contextual_permissions(permission, :project)
return false unless authorizable_user?
return true if admin_and_all_granted_to_admin?(perms)
Project.allowed_to(user, perms).exists?
end
def allowed_in_entity?(permission, entities_to_check, entity_class)
return false if entities_to_check.blank?
return false unless authorizable_user?
perms = contextual_permissions(permission, context_name(entity_class))
entities = Array(entities_to_check)
entities.all? do |entity|
allowed_in_single_entity?(perms, entity)
end
end
def allowed_in_any_entity?(permission, entity_class, in_project: nil)
perms = contextual_permissions(permission, context_name(entity_class))
return false unless authorizable_user?
return true if admin_and_all_granted_to_admin?(perms)
# entity_class.allowed_to will also check whether the user has the permission via a membership in the project.
# ^-- still a problem in some cases
allowed_scope = entity_class.allowed_to(user, perms)
if in_project
allowed_in_single_project?(perms, in_project) || allowed_scope.exists?(project: in_project)
else
allowed_in_any_project?(perms) || allowed_scope.exists?
end
end
private
def cached_permissions(context)
@cached_permissions ||= Hash.new do |hash, context_key|
hash[context_key] = user.all_permissions_for(context_key)
end
@cached_permissions[context]
end
def allowed_in_single_project?(permissions, project)
return false if project.nil?
return false unless project.active? || project.being_archived?
permissions_filtered_for_project = permissions_by_enabled_project_modules(project, permissions)
return false if permissions_filtered_for_project.empty?
return true if admin_and_all_granted_to_admin?(permissions)
cached_permissions(project).intersect?(permissions_filtered_for_project)
end
def allowed_in_single_entity?(permissions, entity)
return false if entity.nil?
return false if entity.project.nil?
return false unless entity.project.active? || entity.project.being_archived?
permissions_filtered_for_project = permissions_by_enabled_project_modules(entity.project, permissions)
return false if permissions_filtered_for_project.empty?
return true if admin_and_all_granted_to_admin?(permissions)
# The combination of this is better then doing
# EntityClass.allowed_to(user, permission).exists?.
# Because this way, all permissions for that context are fetched and cached.
allowed_in_single_project?(permissions, entity.project) ||
cached_permissions(entity).intersect?(permissions_filtered_for_project)
end
def admin_and_all_granted_to_admin?(permissions)
user.admin? && permissions.all?(&:grant_to_admin?)
end
def authorizable_user?
!user.locked? || user.is_a?(SystemUser)
end
def permissions_by_enabled_project_modules(project, permissions)
project
.allowed_permissions
.intersection(permissions.map(&:name))
.map { |perm| perm.name.to_sym }
end
def contextual_permissions(permission, context)
Authorization.contextual_permissions(permission, context, raise_on_unknown: true)
end
def context_name(entity_class)
entity_class.model_name.element.to_sym
end
end
end
``` | require 'rails_helper'
RSpec.describe Authorization::UserPermissibleService do
shared_let(:user) { create(:user) }
shared_let(:anonymous_user) { create(:anonymous) }
shared_let(:project) { create(:project) }
shared_let(:work_package) { create(:work_package, project:) }
shared_let(:non_member_role) { create(:non_member, permissions: [:view_news]) }
shared_let(:anonymous_role) { create(:anonymous_role, permissions: [:view_meetings]) }
let(:queried_user) { user }
subject(:service) { described_class.new(queried_user) }
# The specs in this file do not cover all the various cases yet. Thus,
# we rely on the Authorization.roles scope and the Project/WorkPackage.allowed_to scopes
# to be called which is speced precisely.
shared_examples_for 'the Authorization.roles scope used' do
before do
allow(Authorization)
.to receive(:roles)
.and_call_original
end
it 'calls the Authorization.roles scope once (cached for the second request)' do
subject
subject
expect(Authorization)
.to have_received(:roles)
.once
.with(queried_user, context)
end
end
shared_examples_for 'the Project.allowed_to scope used' do
before do
allow(Project)
.to receive(:allowed_to)
.and_call_original
end
it 'calls the Project.allowed_to scope' do
subject
expect(Project)
.to have_received(:allowed_to) do |user, perm|
expect(user).to eq(queried_user)
expect(perm[0]).to be_a(OpenProject::AccessControl::Permission)
expect(perm[0].name).to eq permission
end
end
end
shared_examples_for 'the WorkPackage.allowed_to scope used' do
before do
allow(WorkPackage)
.to receive(:allowed_to)
.and_call_original
end
it 'calls the WorkPackage.allowed_to scope' do
subject
expect(WorkPackage)
.to have_received(:allowed_to) do |user, perm|
expect(user).to eq(queried_user)
expect(perm[0]).to be_a(OpenProject::AccessControl::Permission)
expect(perm[0].name).to eq permission
end
end
end
describe '#allowed_globally?' do
context 'when asking for a permission that is not defined' do
let(:permission) { :not_defined }
it 'raises an error' do
expect { subject.allowed_globally?(permission) }.to raise_error(Authorization::UnknownPermissionError)
end
end
context 'when asking for a permission that is defined' do
let(:permission) { :create_user }
context 'and the user is a regular user' do
context 'without a role granting the permission' do
it { is_expected.not_to be_allowed_globally(permission) }
end
context 'with a role granting the permission' do
let(:global_role) { create(:global_role, permissions: [permission]) }
let!(:member) { create(:global_member, user:, roles: [global_role]) }
it { is_expected.to be_allowed_globally(permission) }
context 'and the account is locked' do
before { user.locked! }
it { is_expected.not_to be_allowed_globally(permission) }
end
end
end
context 'and the user is an admin' do
let(:user) { create(:admin) }
it { is_expected.to be_allowed_globally(permission) }
context 'and the account is locked' do
before { user.locked! }
it { is_expected.not_to be_allowed_globally(permission) }
end
end
it_behaves_like 'the Authorization.roles scope used' do
let(:context) { nil }
subject { service.allowed_globally?(permission) }
end
end
end
describe '#allowed_in_project?' do
context 'when asking for a permission that is not defined' do
let(:permission) { :not_defined }
it 'raises an error' do
expect { subject.allowed_in_project?(permission, project) }.to raise_error(Authorization::UnknownPermissionError)
end
end
context 'when asking for a permission that is defined' do
let(:permission) { :view_work_packages }
it_behaves_like 'the Authorization.roles scope used' do
let(:context) { project }
subject { service.allowed_in_project?(permission, project) }
end
context 'and the user is not a member of any work package or project' do
it { is_expected.not_to be_allowed_in_project(permission, project) }
context 'and the project is public' do
before { project.update(public: true) }
context 'when requesting a permission that is not granted to the non-member role' do
it { is_expected.not_to be_allowed_in_project(permission, project) }
end
context 'when requesting a permission that is granted to the non-member role' do
let(:permission) { :view_news }
it { is_expected.to be_allowed_in_project(permission, project) }
end
context 'when an anonymous user is requesting a permission that is granted to the anonymous role' do
let(:queried_user) { anonymous_user }
let(:permission) { :view_meetings }
it { is_expected.to be_allowed_in_project(permission, project) }
end
end
end
context 'and the user is a member of a project' do
let(:role) { create(:project_role, permissions: [permission]) }
let!(:project_member) { create(:member, user:, project:, roles: [role]) }
it { is_expected.to be_allowed_in_project(permission, project) }
context 'with the project being archived' do
before { project.update(active: false) }
it { is_expected.not_to be_allowed_in_project(permission, project) }
end
end
context 'and the user is a member of a work package' do
let(:role) { create(:work_package_role, permissions: [permission]) }
let!(:wp_member) { create(:work_package_member, user:, project:, entity: work_package, roles: [role]) }
it { is_expected.not_to be_allowed_in_project(permission, project) }
end
end
end
describe '#allowed_in_any_project?' do
context 'when asking for a permission that is not defined' do
let(:permission) { :not_defined }
it 'raises an error' do
expect { subject.allowed_in_any_project?(permission) }.to raise_error(Authorization::UnknownPermissionError)
end
end
context 'when asking for a permission that is defined' do
let(:permission) { :view_work_packages }
context 'and the user is not a member of any work package or project' do
it { is_expected.not_to be_allowed_in_any_project(permission) }
context 'and the project is public' do
before { project.update_column(:public, true) }
context 'and a permission is requested that is not granted to the non-member role' do
it { is_expected.not_to be_allowed_in_any_project(permission) }
end
context 'and a permission is requested that is granted to the non-member role' do
let(:permission) { :view_news }
it { is_expected.to be_allowed_in_any_project(permission) }
end
context 'and the user is the anonymous user' do
let(:queried_user) { anonymous_user }
let(:permission) { :view_meetings }
it { is_expected.to be_allowed_in_any_project(permission) }
end
context 'and the project is archived' do
before { project.update_column(:active, false) }
it { is_expected.not_to be_allowed_in_any_project(permission) }
end
end
end
context 'and the user is a member of a project' do
let(:role) { create(:project_role, permissions: [permission]) }
let!(:project_member) { create(:member, user:, project:, roles: [role]) }
it { is_expected.to be_allowed_in_any_project(permission) }
context 'and the project is archived' do
before { project.update_column(:active, false) }
it { is_expected.not_to be_allowed_in_any_project(permission) }
end
end
context 'and the user is a member of a work package' do
let(:role) { create(:work_package_role, permissions: [permission]) }
let!(:wp_member) { create(:work_package_member, user:, project:, entity: work_package, roles: [role]) }
it { is_expected.not_to be_allowed_in_any_project(permission) }
context 'and the project is public' do
before { project.update_column(:public, true) }
context 'and a permission is requested that is not granted to the non-member role' do
it { is_expected.not_to be_allowed_in_any_project(permission) }
end
context 'and a permission is requested that is granted to the non-member role' do
let(:permission) { :view_news }
it { is_expected.to be_allowed_in_any_project(permission) }
end
context 'and the project is archived' do
before { project.update_column(:active, false) }
it { is_expected.not_to be_allowed_in_any_project(permission) }
end
end
end
it_behaves_like 'the Project.allowed_to scope used' do
subject { service.allowed_in_any_project?(permission) }
end
end
end
describe '#allowed_in_entity?' do
context 'when asking for a permission that is not defined' do
let(:permission) { :not_defined }
it 'raises an error' do
expect do
subject.allowed_in_entity?(permission, work_package, WorkPackage)
end.to raise_error(Authorization::UnknownPermissionError)
end
end
context 'when asking for a permission that is defined' do
let(:permission) { :view_work_packages }
context 'and the user is not a member of the project or the work package' do
it { is_expected.not_to be_allowed_in_entity(permission, work_package, WorkPackage) }
end
context 'and the user is a member of the project' do
let(:role) { create(:project_role, permissions: [permission]) }
let!(:project_member) { create(:member, user:, project:, roles: [role]) }
it { is_expected.to be_allowed_in_entity(permission, work_package, WorkPackage) }
context 'with the project being archived' do
before { project.update(active: false) }
it { is_expected.not_to be_allowed_in_entity(permission, work_package, WorkPackage) }
end
context 'without the module enabled in the project' do
before { project.enabled_module_names = project.enabled_modules - [:work_package_tracking] }
it { is_expected.not_to be_allowed_in_entity(permission, work_package, WorkPackage) }
end
it_behaves_like 'the Authorization.roles scope used' do
let(:context) { project }
subject { service.allowed_in_entity?(permission, work_package, WorkPackage) }
end
end
context 'and the user is a member of the work package' do
let(:role) { create(:work_package_role, permissions: [permission]) }
let!(:wp_member) { create(:work_package_member, user:, project:, entity: work_package, roles: [role]) }
it { is_expected.to be_allowed_in_entity(permission, work_package, WorkPackage) }
context 'with the project being archived' do
before { project.update(active: false) }
it { is_expected.not_to be_allowed_in_entity(permission, work_package, WorkPackage) }
end
it_behaves_like 'the Authorization.roles scope used' do
let(:context) { work_package }
subject { service.allowed_in_entity?(permission, work_package, WorkPackage) }
end
end
context 'and user is member in the project (not granting the permission) and the work package (granting the permission)' do
let(:permission) { :edit_work_packages }
let(:role) { create(:project_role, permissions: [:view_work_packages]) }
let!(:project_member) { create(:member, user:, project:, roles: [role]) }
let(:wp_role) { create(:work_package_role, permissions: [permission]) }
let!(:wp_member) { create(:work_package_member, user:, project:, entity: work_package, roles: [wp_role]) }
it { is_expected.to be_allowed_in_entity(permission, work_package, WorkPackage) }
it_behaves_like 'the Authorization.roles scope used' do
let(:context) { work_package }
subject { service.allowed_in_entity?(permission, work_package, WorkPackage) }
end
end
end
end
describe '#allowed_in_any_entity?' do
context 'when asking for a permission that is not defined' do
let(:permission) { :not_defined }
it 'raises an error' do
expect { subject.allowed_in_any_entity?(permission, WorkPackage) }.to raise_error(Authorization::UnknownPermissionError)
end
end
context 'when asking for a permission that is defined' do
let(:permission) { :view_work_packages }
context 'and the user is not a member of any work package or project' do
it { is_expected.not_to be_allowed_in_any_entity(permission, WorkPackage) }
end
context 'and the user is a member of a project' do
let(:role) { create(:project_role, permissions: [permission]) }
let!(:project_member) { create(:member, user:, project:, roles: [role]) }
it { is_expected.to be_allowed_in_any_entity(permission, WorkPackage) }
context 'when specifying the same project' do
it { is_expected.to be_allowed_in_any_entity(permission, WorkPackage, in_project: project) }
end
context 'when specifying a different project' do
let(:other_project) { create(:project) }
it { is_expected.not_to be_allowed_in_any_entity(permission, WorkPackage, in_project: other_project) }
end
end
context 'and the user is a member of a work package' do
let(:role) { create(:work_package_role, permissions: [permission]) }
let!(:wp_member) { create(:work_package_member, user:, project:, entity: work_package, roles: [role]) }
it { is_expected.to be_allowed_in_any_entity(permission, WorkPackage) }
end
it_behaves_like 'the WorkPackage.allowed_to scope used' do
subject { service.allowed_in_any_entity?(permission, WorkPackage) }
end
it_behaves_like 'the WorkPackage.allowed_to scope used' do
subject { service.allowed_in_any_entity?(permission, WorkPackage, in_project: project) }
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 Authorization::UserEntityRolesQuery < Authorization::UserRolesQuery
transformations.register :all, :user_restriction do |statement, user, _|
statement.where(users_table[:id].eq(user.id))
end
transformations.register users_members_join, :entity_restriction do |statement, _, entity|
statement = statement
.and(members_table[:entity_type].eq(entity.class.to_s))
.and(members_table[:entity_id].eq(entity.id))
statement = statement.and(members_table[:project_id].eq(entity.project_id)) if entity.respond_to?(:project_id)
statement
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::UserEntityRolesQuery do
let(:user) { build(:user) }
let(:project) { build(:project, public: false) }
let(:work_package) { build(:work_package, project:) }
let(:work_package2) { build(:work_package, project:) }
let(:role) { build(:project_role) }
let(:wp_role) { build(:work_package_role) }
let(:other_wp_role) { build(:work_package_role) }
let(:non_member) { build(:non_member) }
let(:member) { build(:member, project:, roles: [wp_role], principal: user, entity: work_package) }
let(:project_member) { build(:member, project:, roles: [role], principal: user) }
let(:other_member) { build(:member, project:, roles: [other_wp_role], principal: user, entity: work_package2) }
describe '.query' do
before do
non_member.save!
user.save!
end
it 'is a relation' do
expect(described_class.query(user, work_package)).to be_a ActiveRecord::Relation
end
context 'with the user being a member of the work package' do
before do
member.save!
end
it 'returns the work package role' do
expect(described_class.query(user, work_package)).to contain_exactly(wp_role)
end
context 'when the user also has a membership with a different role on another work package' do
before do
other_member.save!
end
it 'does not include the second role' do
expect(described_class.query(user, work_package)).not_to include(other_wp_role)
end
end
context 'when the user also has a membership with a different role on the project' do
before do
project_member.save!
end
it 'does not include the second role' do
expect(described_class.query(user, work_package)).not_to include(role)
end
end
end
context 'without the user being member in the work package' do
it 'is empty' do
expect(described_class.query(user, work_package)).to be_empty
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 Authorization::UserAllowedService
attr_accessor :user
def initialize(user, role_cache: Users::ProjectRoleCache.new(user))
self.user = user
self.project_role_cache = role_cache
end
# Return true if the user is allowed to do the specified action on a specific context
# Action can be:
# * a parameter-like Hash (eg. { controller: '/projects', action: 'edit' })
# * a permission Symbol (eg. :edit_project)
# Context can be:
# * a project : returns true if user is allowed to do the specified action on this project
# * a group of projects : returns true if user is allowed on every project
# * an entity that a user can become a member of specifically (listed in Member::ALLOWED_ENTITIES) :
# * returns true if user is allowed to do the specified action on the given item or
# * returns ture if user is allowed to do the specified action on the project the entity belongs to
# * nil with +global+ set to +true+ : check if user has at least one role allowed for this action,
# or falls back to Non Member / Anonymous permissions depending if the user is logged
def call(action, context, global: false)
if supported_context?(context, global:)
allowed_to?(action, context, global:)
else
false
end
end
def preload_projects_allowed_to(action)
project_authorization_cache.cache(action)
end
private
attr_accessor :project_role_cache
def allowed_to?(action, context, global: false)
action = normalize_action(action)
if context.nil? && global
allowed_to_globally?(action)
elsif context.is_a? Project
allowed_to_in_project?(action, context)
elsif supported_entity?(context)
allowed_to_in_entity?(action, context)
elsif context.respond_to?(:to_a)
allowed_to_in_all_projects?(action, context)
else
false
end
end
def allowed_to_in_entity?(action, entity)
# Inactive users are never authorized
return false unless authorizable_user?
# Short circuit: When the user is already allowed to execute the action baed
# on the project, there's no need to do a check on the entity
return true if entity.respond_to?(:project) && allowed_to_in_project?(action, entity.project)
# Admin users are authorized for anything else
# unless the permission is explicitly flagged not to be granted to admins.
return true if granted_to_admin?(action)
has_authorized_role?(action, entity)
end
def allowed_to_in_project?(action, project)
return false if project.nil?
if project_authorization_cache.cached?(action)
return project_authorization_cache.allowed?(action, project)
end
# No action allowed on archived projects
return false unless project.active? || project.being_archived?
# No action allowed on disabled modules
return false unless project.allows_to?(action)
# Inactive users are never authorized
return false unless authorizable_user?
# Admin users are authorized for anything else
# unless the permission is explicitly flagged not to be granted to admins.
return true if granted_to_admin?(action)
has_authorized_role?(action, project)
end
# Authorize if user is authorized on every element of the array
def allowed_to_in_all_projects?(action, projects)
projects.present? && Array(projects).all? do |project|
allowed_to?(action, project)
end
end
# Is the user allowed to do the specified action on any project?
# See allowed_to? for the action parameter description.
def allowed_to_globally?(action)
# Inactive users are never authorized
return false unless authorizable_user?
# Admin users are always authorized
return true if granted_to_admin?(action)
has_authorized_role?(action)
end
##
# Only users that are not locked may be granted actions
# with the exception of a temporary-granted system user
def authorizable_user?
!user.locked? || user.is_a?(SystemUser)
end
# Admin users are granted every permission unless the
# permission explicitly disables it.
def granted_to_admin?(action)
user.admin? && OpenProject::AccessControl.grant_to_admin?(action)
end
def has_authorized_role?(action, context = nil)
project_role_cache
.fetch(context)
.any? do |role|
role.allowed_to?(action)
end
end
def project_authorization_cache
@project_authorization_cache ||= Users::ProjectAuthorizationCache.new(user)
end
def normalize_action(action)
if action.is_a?(Hash) && action[:controller] && action[:controller].to_s.starts_with?('/')
action = action.dup
action[:controller] = action[:controller][1..]
end
action
end
def supported_context?(context, global:)
(context.nil? && global) ||
context.is_a?(Project) ||
supported_entity?(context) ||
(!context.nil? && context.respond_to?(:to_a))
end
def supported_entity?(entity)
Member.can_be_member_of?(entity)
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'
# TODO: Fix tests here
RSpec.describe Authorization::UserAllowedService do
let(:user) { build_stubbed(:user) }
let(:instance) { described_class.new(user) }
let(:action) { :an_action }
let(:action_hash) { { controller: '/controller', action: 'action' } }
let(:project) { build_stubbed(:project) }
let(:other_project) { build_stubbed(:project) }
let(:role) { build_stubbed(:project_role) }
let(:user_roles_in_project) do
array = [role]
allow(array)
.to receive(:eager_load)
.and_return(array)
array
end
let(:role_grants_action) { true }
let(:project_allows_to) { true }
subject { instance.call(action, context) }
describe '#initialize' do
it 'has the user' do
expect(instance.user).to eql user
end
end
shared_examples_for 'allowed to checked' do
before do
Array(context).each do |project|
project.active = true
allow(project).to receive(:allows_to?).with(action).and_return(project_allows_to)
allow(Authorization).to receive(:roles).with(user, project).and_return(user_roles_in_project)
end
allow(role).to receive(:allowed_to?).with(action).and_return(role_grants_action)
end
context 'with the user having a granting role' do
it 'is true' do
expect(subject).to be_truthy
end
it 'does not call the db twice for a project' do
Array(context).each do |project|
allow(Authorization).to receive(:roles).with(user, project).and_return(user_roles_in_project)
end
subject
subject
Array(context).each do |project|
expect(Authorization)
.to have_received(:roles)
.once
.with(user, project)
end
end
context 'but the user not being active' do
before do
user.lock
end
it 'returns false', :aggregate_failures do
expect(instance.call(action, nil, global: true)).not_to be_truthy
end
end
end
context 'with the user having a nongranting role' do
let(:role_grants_action) { false }
it 'is false' do
expect(subject).to be_falsey
end
end
context 'with the user being admin
with the user not having a granting role' do
let(:user_roles_in_project) { [] }
before do
user.admin = true
end
it 'is true' do
expect(subject).to be_truthy
end
end
context 'with the project not being active' do
before do
Array(context).each do |project|
project.active = false
project.clear_changes_information
end
end
it 'is false' do
expect(subject).to be_falsey
end
it 'is false even if the user is admin' do
user.admin = true
expect(subject).to be_falsey
end
end
context 'with the project being archived' do
before do
Array(context).each do |project|
project.active = false
end
end
it 'is true' do
expect(subject).to be_truthy
end
end
context 'with the project not having the action enabled' do
let(:project_allows_to) { false }
it 'is false' do
expect(subject).to be_falsey
end
it 'is false even if the user is admin' do
user.admin = true
expect(subject).to be_falsey
end
end
context 'with having precached the results' do
before do
auth_cache = double('auth_cache')
allow(Users::ProjectAuthorizationCache)
.to receive(:new)
.and_return(auth_cache)
allow(auth_cache)
.to receive(:cache)
.with(action)
allow(auth_cache)
.to receive(:cached?)
.with(action)
.and_return(true)
Array(context).each do |project|
allow(auth_cache)
.to receive(:allowed?)
.with(action, project)
.and_return(true)
end
instance.preload_projects_allowed_to(action)
end
it 'is true' do
expect(subject).to be_truthy
end
it 'does not call the db' do
subject
expect(Authorization)
.not_to have_received(:roles)
end
end
end
describe '#call' do
context 'for a project' do
let(:context) { project }
it_behaves_like 'allowed to checked'
end
context 'for an array of projects' do
let(:context) { [project, other_project] }
it_behaves_like 'allowed to checked'
it 'is false' do
expect(instance.call(action, [])).to be_falsey
end
context 'with one project not allowing an action' do
before do
allow(project)
.to receive(:allows_to?)
.with(action)
.and_return(false)
end
it 'is false' do
expect(instance.call(action, [project, other_project])).to be_falsey
end
end
end
context 'for a relation of projects' do
let(:context) { double('relation', class: ActiveRecord::Relation, to_a: [project]) }
it_behaves_like 'allowed to checked'
end
context 'for anything else' do
let(:context) { nil }
it 'is false' do
expect(subject).to be_falsey
end
end
context 'for a global check' do
context 'with the user being admin' do
before do
user.admin = true
end
it 'is true' do
expect(instance.call(action, nil, global: true)).to be_truthy
end
end
context 'with the user having a granting role' do
before do
allow(Authorization).to receive(:roles).with(user, nil).and_return(user_roles_in_project)
allow(role).to receive(:allowed_to?).with(action).and_return(true)
end
context 'but the user not being active' do
before do
user.lock
end
it 'is unsuccessful', :aggregate_failures do
expect(instance.call(action, nil, global: true)).not_to be_truthy
end
end
it 'is successful', :aggregate_failures do
expect(instance.call(action, nil, global: true)).to be_truthy
end
end
context 'with the user not having a granting role' do
before do
allow(Authorization).to receive(:roles).with(user, nil).and_return(user_roles_in_project)
allow(role).to receive(:allowed_to?).with(action).and_return(false)
end
it 'is false' do
expect(instance.call(action, nil, global: true)).to be_falsey
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 Authorization::UserGlobalRolesQuery < Authorization::UserRolesQuery
transformations.register roles_member_roles_join,
:builtin_role do |statement, user|
builtin_role = if user.logged?
Role::BUILTIN_NON_MEMBER
else
Role::BUILTIN_ANONYMOUS
end
builtin_role_condition = roles_table[:builtin].eq(builtin_role)
statement.or(builtin_role_condition)
end
transformations.register :all, :global_group_where_projection do |statement, user|
statement.group(roles_table[:id])
.where(users_table[:id].eq(user.id))
end
transformations.register users_members_join, :entity_restriction do |statement, _|
statement
.and(members_table[:entity_type].eq(nil))
.and(members_table[:entity_id].eq(nil))
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::UserGlobalRolesQuery do
let(:user) { build(:user) }
let(:anonymous) { build(:anonymous) }
let(:project) { build(:project, public: false) }
let(:project2) { build(:project, public: false) }
let(:public_project) { build(:project, public: true) }
let(:role) { build(:project_role) }
let(:role2) { build(:project_role) }
let(:anonymous_role) { build(:anonymous_role) }
let(:non_member) { build(:non_member) }
let(:member) do
build(:member, project:,
roles: [role],
principal: user)
end
let(:member2) do
build(:member, project: project2,
roles: [role2],
principal: user)
end
let(:global_permission) { OpenProject::AccessControl.permissions.find(&:global?) }
let(:global_role) do
build(:global_role,
permissions: [global_permission.name])
end
let(:global_member) do
build(:global_member,
principal: user,
roles: [global_role])
end
let(:work_package_permission) { [:edit_work_packages] }
let(:work_package_editor_role) { create(:work_package_role, permissions: work_package_permission) }
let(:work_package) { create(:work_package, project:) }
let(:work_package_member) do
build(:member, entity: work_package, project: work_package.project, roles: [work_package_editor_role], principal: user)
end
describe '.query' do
before do
non_member.save!
anonymous_role.save!
user.save!
end
it 'is a user relation' do
expect(described_class.query(user, project)).to be_a ActiveRecord::Relation
end
context 'with the user being a member in a project' do
before do
member.save!
end
it 'is the member and non member role' do
expect(described_class.query(user)).to contain_exactly(role, non_member)
end
end
context 'with the user being a member in two projects' do
before do
member.save!
member2.save!
end
it 'is both member and the non member role' do
expect(described_class.query(user)).to contain_exactly(role, role2, non_member)
end
end
context 'without the user being a member in a project' do
it 'is the non member role' do
expect(described_class.query(user)).to contain_exactly(non_member)
end
end
context 'with the user being anonymous' do
it 'is the anonymous role' do
expect(described_class.query(anonymous)).to contain_exactly(anonymous_role)
end
end
context 'with the user having a global role' do
before do
global_member.save!
end
it 'is the global role and non member role' do
expect(described_class.query(user)).to contain_exactly(global_role, non_member)
end
end
context 'with the user having a global role and a member role' do
before do
member.save!
global_member.save!
end
it 'is the global role, member role and non member role' do
expect(described_class.query(user)).to contain_exactly(global_role, role, non_member)
end
end
context 'with the user having a global role, a member role and a work package role' do
before do
member.save!
global_member.save!
work_package_member.save!
end
it 'is the global role, member role and non member role' do
expect(described_class.query(user)).to contain_exactly(global_role, role, non_member)
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 Authentication
class OmniauthService
include Contracted
attr_accessor :auth_hash,
:strategy,
:controller,
:contract,
:user_attributes,
:identity_url,
:user
delegate :session, to: :controller
def initialize(strategy:, auth_hash:, controller:)
self.strategy = strategy
self.auth_hash = auth_hash
self.controller = controller
self.contract = ::Authentication::OmniauthAuthHashContract.new(auth_hash)
end
def call(additional_user_params = nil)
inspect_response(Logger::DEBUG)
unless contract.validate
result = ServiceResult.failure(errors: contract.errors)
Rails.logger.error do
"[OmniAuth strategy #{strategy.name}] Failed to process omniauth response for #{auth_uid}: #{result.message}"
end
inspect_response(Logger::ERROR)
return result
end
# Create or update the user from omniauth
# and assign non-nil parameters from the registration form - if any
assignable_params = (additional_user_params || {}).reject { |_, v| v.nil? }
update_user_from_omniauth!(assignable_params)
# If we have a new or invited user, we still need to register them
call = activate_user!
# Update the admin flag when present successful
call = update_admin_flag(call) if call.success?
# The user should be logged in now
tap_service_result call
end
private
##
# Inspect the response object, trying to find out what got returned
def inspect_response(log_level)
case strategy
when ::OmniAuth::Strategies::SAML
::OpenProject::AuthSaml::Inspector.inspect_response(auth_hash) do |message|
Rails.logger.add log_level, message
end
else
Rails.logger.add(log_level) do
"[OmniAuth strategy #{strategy.name}] Returning from omniauth with hash " \
"#{auth_hash&.to_hash.inspect} Valid? #{auth_hash&.valid?}"
end
end
rescue StandardError => e
OpenProject.logger.error "[OmniAuth strategy #{strategy&.name}] Failed to inspect OmniAuth response: #{e.message}"
end
##
# After login flow
def tap_service_result(call)
if call.success? && user.active?
OpenProject::Hook.call_hook :omniauth_user_authorized, { auth_hash:, controller: }
# Call deprecated login hook
OpenProject::OmniAuth::Authorization.after_login! user, auth_hash, self
end
call
end
##
# After validating the omniauth hash
# and the authorization is successful,
#
# login the user by locating or creating it
def update_user_from_omniauth!(additional_user_params)
# Find or create the user from the auth hash
self.user_attributes = build_omniauth_hash_to_user_attributes.merge(additional_user_params)
self.identity_url = user_attributes[:identity_url]
self.user = lookup_or_initialize_user
# Assign or update the user with the omniauth attributes
update_attributes
end
##
# Try to find or create the user
# in the following order:
#
# 1. Look for an active invitation token
# 2. Look for an existing user for the current identity_url
# 3. Look for an existing user that we can remap (IF remapping is allowed)
# 4. Try to register a new user and activate according to settings
def lookup_or_initialize_user
find_invited_user ||
find_existing_user ||
remap_existing_user ||
initialize_new_user
end
##
# Return an invited user, if there is a token
def find_invited_user
return unless session.include?(:invitation_token)
tok = Token::Invitation.find_by value: session[:invitation_token]
return unless tok
tok.user.tap do |user|
user.identity_url = user_attributes[:identity_url]
tok.destroy
session.delete :invitation_token
end
end
##
# Find an existing user by the identity url
def find_existing_user
User.find_by(identity_url:)
end
##
# Allow to map existing users with an Omniauth source if the login
# already exists, and no existing auth source or omniauth provider is
# linked
def remap_existing_user
return unless Setting.oauth_allow_remapping_of_existing_users?
User.not_builtin.find_by_login(user_attributes[:login]) # rubocop:disable Rails/DynamicFindBy
end
##
# Create the new user and try to activate it
# according to settings and system limits
def initialize_new_user
User.new(identity_url: user_attributes[:identity_url])
end
##
# Update or assign the user attributes
def update_attributes
if user.new_record? || user.invited?
user.register unless user.invited?
::Users::SetAttributesService
.new(user: User.system, model: user, contract_class: ::Users::UpdateContract)
.call(user_attributes)
else
# Update the user, but do not change the admin flag
# as this call is not validated.
# we do this separately in +update_admin_flag+
::Users::UpdateService
.new(user: User.system, model: user)
.call(user_attributes.except(:admin))
end
end
def update_admin_flag(call)
return call unless user_attributes.key?(:admin)
new_admin = ActiveRecord::Type::Boolean.new.cast(user_attributes[:admin])
return call if user.admin == new_admin
::Users::UpdateService
.new(user: User.system, model: user)
.call(admin: new_admin)
.on_failure { |res| update_admin_flag_failure(res) }
.on_success { update_admin_flag_success(new_admin) }
end
def update_admin_flag_success(new_admin)
if new_admin
OpenProject.logger.info { "[OmniAuth strategy #{strategy.name}] Granted user##{update.result.id} admin permissions" }
else
OpenProject.logger.info { "[OmniAuth strategy #{strategy.name}] Revoked user##{update.result.id} admin permissions" }
end
end
def update_admin_flag_failure(call)
OpenProject.logger.error do
"[OmniAuth strategy #{strategy.name}] Failed to update admin user permissions: #{call.message}"
end
end
def activate_user!
if activatable?
::Users::RegisterUserService
.new(user)
.call
else
ServiceResult.success(result: user)
end
end
##
# Determines if the given user is activatable on the fly, that is:
#
# 1. The user has just been initialized by us
# 2. The user has been invited
# 3. The user had been registered manually (e.g., through a previous self-registration setting)
def activatable?
user.new_record? || user.invited? || user.registered?
end
##
# Maps the omniauth attribute hash
# to our internal user attributes
def build_omniauth_hash_to_user_attributes
info = auth_hash[:info]
attribute_map = {
login: info[:login] || info[:email],
mail: info[:email],
firstname: info[:first_name] || info[:name],
lastname: info[:last_name],
identity_url: identity_url_from_omniauth,
}
# Map the admin attribute if provided in an attribute mapping
attribute_map[:admin] = ActiveRecord::Type::Boolean.new.cast(info[:admin]) if info.key?(:admin)
# Allow strategies to override mapping
if strategy.respond_to?(:omniauth_hash_to_user_attributes)
attribute_map.merge!(strategy.omniauth_hash_to_user_attributes(auth_hash))
end
# Remove any nil values to avoid
# overriding existing attributes
attribute_map.reject! { |_, value| value.nil? || value == '' }
Rails.logger.debug { "Mapped auth_hash user attributes #{attribute_map.inspect}" }
attribute_map
end
##
# Allow strategies to map a value for uid instead
# of always taking the global UID.
# For SAML, the global UID may change with every session
# (in case of transient nameIds)
def identity_url_from_omniauth
identifier = auth_hash[:info][:uid] || auth_hash[:uid]
"#{auth_hash[:provider]}:#{identifier}"
end
##
# Try to provide some context of the auth_hash in case of errors
def auth_uid
hash = (auth_hash || {})
hash.dig(:info, :uid) || hash.dig(:uid) || 'unknown'
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 Authentication::OmniauthService do
let(:strategy) { double('Omniauth Strategy', name: 'saml') }
let(:additional_info) do
{}
end
let(:auth_hash) do
OmniAuth::AuthHash.new(
provider: 'google',
uid: '123545',
info: {
name: 'foo',
email: auth_email,
first_name: 'foo',
last_name: 'bar'
}.merge(additional_info)
)
end
let(:auth_email) { '[email protected]' }
let(:controller) { double('Controller', session: session_stub) }
let(:session_stub) { [] }
let(:instance) { described_class.new(strategy:, auth_hash:, controller:) }
let(:user_attributes) { instance.send :build_omniauth_hash_to_user_attributes }
describe '#contract' do
before do
allow(instance.contract)
.to(receive(:validate))
.and_return(valid)
end
context 'if valid' do
let(:valid) { true }
it 'calls the registration service' do
expect(Users::RegisterUserService)
.to(receive(:new))
.with(kind_of(User))
.and_call_original
instance.call
end
end
context 'if invalid' do
let(:valid) { false }
it 'does not call the registration service' do
expect(Users::RegisterUserService)
.not_to(receive(:new))
expect(instance.contract)
.to(receive(:errors))
.and_return(['foo'])
call = instance.call
expect(call).to be_failure
expect(call.errors).to eq ['foo']
end
end
end
describe 'activation of users' do
let(:call) { instance.call }
context 'with an active found user' do
shared_let(:user) { create(:user, login: '[email protected]', identity_url: 'google:123545') }
it 'does not call register user service and logs in the user' do
allow(Users::RegisterUserService).to receive(:new)
expect(OpenProject::OmniAuth::Authorization)
.to(receive(:after_login!))
.with(user, auth_hash, instance)
expect(call).to be_success
expect(call.result).to eq user
expect(call.result.firstname).to eq 'foo'
expect(call.result.lastname).to eq 'bar'
expect(call.result.mail).to eq '[email protected]'
expect(Users::RegisterUserService).not_to have_received(:new)
end
context 'if the user is to become admin' do
let(:additional_info) { { admin: true } }
it 'updates the user' do
expect(user).not_to be_admin
expect(call).to be_success
expect(call.result).to eq user
expect(call.result).to be_admin
end
context 'if the user cannot be updated for some reason' do
let(:stub) { instance_double(Users::UpdateService) }
it 'fails the request' do
allow(Users::UpdateService).to receive(:new).and_return(stub)
allow(stub).to receive(:call).and_return(ServiceResult.failure(message: 'Oh noes!'))
expect(call).not_to be_success
expect(call.result).to be_nil
expect(user.reload).not_to be_admin
end
end
end
context 'if the user is the last admin and is about to be revoked' do
let(:additional_info) { { admin: false } }
it 'does not revoke admin status' do
user.update!(admin: true)
expect(user).to be_admin
expect(call).not_to be_success
expect(call.result).to eq user
expect(user.reload).to be_admin
expect(call.errors.details[:base]).to contain_exactly({ error: :one_must_be_active })
end
end
context 'if the user is not the last admin and is about to be revoked' do
let!(:other_admin) { create(:admin) }
let(:additional_info) { { admin: false } }
it 'revokes admin status' do
user.update!(admin: true)
expect(user).to be_admin
expect(call).to be_success
expect(call.result).to eq user
expect(user.reload).not_to be_admin
end
end
end
context 'without remapping allowed',
with_settings: { oauth_allow_remapping_of_existing_users?: false } do
let!(:user) { create(:user, login: '[email protected]') }
it 'does not look for the user by login' do
allow(Users::RegisterUserService).to receive(:new).and_call_original
expect(call).not_to be_success
expect(call.result.firstname).to eq 'foo'
expect(call.result.lastname).to eq 'bar'
expect(call.result.mail).to eq '[email protected]'
expect(call.result).not_to eq user
expect(call.result).to be_new_record
expect(call.result.errors[:login]).to eq ['has already been taken.']
expect(Users::RegisterUserService).to have_received(:new)
end
end
context 'with an active user remapped',
with_settings: { oauth_allow_remapping_of_existing_users?: true } do
let!(:user) { create(:user, identity_url: 'foo', login: auth_email.downcase) }
shared_examples_for 'a successful remapping of foo' do
before do
allow(Users::RegisterUserService).to receive(:new)
allow(OpenProject::OmniAuth::Authorization)
.to(receive(:after_login!))
.with(user, auth_hash, instance)
end
it 'does not call register user service and logs in the user' do
aggregate_failures 'Service call' do
expect(call).to be_success
expect(call.result).to eq user
expect(call.result.firstname).to eq 'foo'
expect(call.result.lastname).to eq 'bar'
expect(call.result.login).to eq auth_email
expect(call.result.mail).to eq auth_email
end
user.reload
aggregate_failures 'User attributes' do
expect(user.firstname).to eq 'foo'
expect(user.lastname).to eq 'bar'
expect(user.identity_url).to eq 'google:123545'
end
aggregate_failures 'Message expectations' do
expect(OpenProject::OmniAuth::Authorization)
.to(have_received(:after_login!))
expect(Users::RegisterUserService).not_to have_received(:new)
end
end
end
context 'with an all lower case login on the IdP side' do
it_behaves_like 'a successful remapping of foo'
end
context 'with a partially upper case login on the IdP side' do
let(:auth_email) { '[email protected]' }
it_behaves_like 'a successful remapping of foo'
end
end
describe 'assuming registration/activation worked' do
let(:register_call) { ServiceResult.new(success: register_success, message: register_message) }
let(:register_success) { true }
let(:register_message) { 'It worked!' }
before do
expect(Users::RegisterUserService).to receive_message_chain(:new, :call).and_return(register_call)
end
describe 'with a new user' do
it 'calls the register service' do
expect(call).to be_success
# The user might get activated in the register service
expect(instance.user).not_to be_active
expect(instance.user).to be_new_record
# Expect notifications to be present (Regression #38066)
expect(instance.user.notification_settings).not_to be_empty
end
end
end
describe 'assuming registration/activation failed' do
let(:register_success) { false }
let(:register_message) { 'Oh noes :(' }
end
end
describe '#identity_url_from_omniauth' do
let(:auth_hash) { { provider: 'developer', uid: 'veryuniqueid', info: {} } }
subject { instance.send(:identity_url_from_omniauth) }
it 'returns the correct identity_url' do
expect(subject).to eql('developer:veryuniqueid')
end
context 'with uid mapped from info' do
let(:auth_hash) { { provider: 'developer', uid: 'veryuniqueid', info: { uid: 'internal' } } }
it 'returns the correct identity_url' do
expect(subject).to eql('developer:internal')
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 Backups
class CreateService < ::BaseServices::Create
def initialize(user:, backup_token:, include_attachments: true, contract_class: ::Backups::CreateContract)
super user:, contract_class:, contract_options: { backup_token: }
@include_attachments = include_attachments
end
def include_attachments?
@include_attachments
end
def after_perform(call)
if call.success?
BackupJob.perform_later(
backup: call.result,
user:,
include_attachments: include_attachments?
)
end
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_create_service'
RSpec.describe Backups::CreateService, type: :model do
let(:user) { create(:admin) }
let(:service) { described_class.new user:, backup_token: backup_token.plain_value }
let(:backup_token) { create(:backup_token, user:) }
it_behaves_like 'BaseServices create service' do
let(:instance) { service }
let(:backup_token) { build_stubbed(:backup_token, user:) }
let(:contract_options) { { backup_token: backup_token.plain_value } }
end
context "with right permissions" do
context "with no further options" do
it "enqueues a BackupJob which includes attachments" do
expect { service.call }.to have_enqueued_job(BackupJob).with do |args|
expect(args["include_attachments"]).to be true
end
end
end
context "with include_attachments: false" do
let(:service) do
described_class.new user:, backup_token: backup_token.plain_value, include_attachments: false
end
it "enqueues a BackupJob which does not include attachments" do
expect(BackupJob)
.to receive(:perform_later)
.with(hash_including(include_attachments: false, user:))
expect(service.call).to be_success
end
end
end
context "with missing permission" do
let(:user) { create(:user) }
it "does not enqueue a BackupJob" do
expect { expect(service.call).to be_failure }.not_to have_enqueued_job(BackupJob)
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 Notifications
class SetAttributesService < ::BaseServices::SetAttributes
private
def set_default_attributes(params)
super
set_default_project unless model.project
end
##
# Try to determine the project context from the journal (if any)
# or the resource if it has a project set
def set_default_project
model.project = model.journal&.project || model.resource.try(:project)
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 Notifications::SetAttributesService, type: :model do
let(:user) { build_stubbed(:user) }
let(:contract_class) do
contract = double('contract_class')
allow(contract)
.to receive(:new)
.with(event, 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: event,
contract_class:)
end
let(:call_attributes) { {} }
let(:project) { build_stubbed(:project) }
let(:reason) { :mentioned }
let(:journal) { build_stubbed(:journal, journable:, data: journal_data) }
let(:journable) { nil }
let(:journal_data) { nil }
let(:event_subject) { 'I find it important' }
let(:recipient_id) { 1 }
describe 'call' do
let(:call_attributes) do
{
recipient_id:,
reason:,
resource: journable,
journal:,
subject: event_subject,
project:
}
end
subject { instance.call(call_attributes) }
context 'for a new record' do
let(:event) do
Notification.new
end
it 'is successful' do
expect(subject)
.to be_success
end
it 'sets the attributes add adds default values' do
subject
expect(event.attributes.compact.symbolize_keys)
.to eql({
project_id: project.id,
reason: 'mentioned',
journal_id: journal.id,
recipient_id: 1,
subject: event_subject,
read_ian: false,
mail_reminder_sent: false
})
end
context 'with only the minimal set of attributes for a notification' do
let(:journable) do
build_stubbed(:work_package, project:).tap do |wp|
allow(wp)
.to receive(:to_s)
.and_return("wp to s")
end
end
let(:journal_data) do
build_stubbed(:journal_work_package_journal, project:)
end
let(:call_attributes) do
{
recipient_id:,
reason:,
journal:,
resource: journable
}
end
it 'sets the attributes and adds default values that are deduced' do
subject
expect(event.attributes.compact.symbolize_keys)
.to eql({
project_id: project.id,
reason: 'mentioned',
resource_id: journable.id,
resource_type: 'WorkPackage',
journal_id: journal.id,
recipient_id: 1,
read_ian: false,
mail_reminder_sent: false
})
end
end
it 'does not persist the notification' do
expect(event)
.not_to receive(:save)
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.
#++
module Notifications
class MailService
include WithMarkedNotifications
def initialize(notification)
self.notification = notification
end
def call
return unless supported?
return if ian_read?
with_marked_notifications(notification.id) do
strategy.send_mail(notification)
end
end
private
attr_accessor :notification
def ian_read?
notification.read_ian
end
def strategy
@strategy ||= if self.class.const_defined?("#{strategy_model}Strategy")
"#{self.class}::#{strategy_model}Strategy".constantize
end
end
def strategy_model
journal&.journable_type || resource&.class
end
def journal
notification.journal
end
def resource
notification.resource
end
def supported?
strategy.present?
end
def notification_marked_attribute
:mail_alert_sent
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 Notifications::MailService, type: :model do
require_relative './mentioned_journals_shared'
subject(:call) { instance.call }
let(:recipient) do
build_stubbed(:user,
preference: build_stubbed(:user_preference,
settings: {
immediate_reminders: {
mentioned: immediate_reminders_mentioned
}
}))
end
let(:actor) do
build_stubbed(:user)
end
let(:instance) { described_class.new(notification) }
let(:immediate_reminders_mentioned) { true }
context 'with a work package journal notification' do
let(:journal) do
build_stubbed(:work_package_journal).tap do |j|
allow(j)
.to receive(:initial?)
.and_return(journal_initial)
end
end
let(:read_ian) { false }
let(:reason) { :mentioned }
let(:notification) do
build_stubbed(:notification,
journal:,
recipient:,
actor:,
reason:,
read_ian:)
end
let(:journal_initial) { false }
let(:mail) do
mail = instance_double(ActionMailer::MessageDelivery)
allow(WorkPackageMailer)
.to receive(:mentioned)
.and_return(mail)
allow(mail)
.to receive(:deliver_later)
mail
end
before do
mail
end
shared_examples_for 'sends a mentioned mail' do
it 'sends a mail' do
call
expect(WorkPackageMailer)
.to have_received(:mentioned)
.with(recipient,
journal)
expect(mail)
.to have_received(:deliver_later)
end
end
shared_examples_for 'sends no mentioned mail' do
it 'sends no mail' do
call
expect(WorkPackageMailer)
.not_to have_received(:mentioned)
end
end
context 'with the notification mentioning the user' do
it_behaves_like 'sends a mentioned mail'
end
context 'with the notification not mentioning the user' do
let(:reason) { false }
it_behaves_like 'sends no mentioned mail'
end
context 'with the notification mentioning the user but with the recipient having deactivated the mail' do
let(:immediate_reminders_mentioned) { false }
it_behaves_like 'sends no mentioned mail'
end
end
context 'with a wiki_content journal notification' do
let(:journal) do
build_stubbed(:wiki_page_journal,
journable: build_stubbed(:wiki_page)).tap do |j|
allow(j)
.to receive(:initial?)
.and_return(journal_initial)
end
end
let(:read_ian) { false }
let(:notification) do
build_stubbed(:notification,
journal:,
recipient:,
actor:,
read_ian:)
end
let(:mail) do
mail = instance_double(ActionMailer::MessageDelivery)
allow(UserMailer)
.to receive(:wiki_page_added)
.and_return(mail)
allow(UserMailer)
.to receive(:wiki_page_updated)
.and_return(mail)
allow(mail)
.to receive(:deliver_now)
mail
end
let(:journal_initial) { false }
before do
mail
end
context 'with the notification being for an initial journal' do
let(:journal_initial) { true }
it 'sends a mail' do
call
expect(UserMailer)
.to have_received(:wiki_page_added)
.with(recipient,
journal.journable)
expect(mail)
.to have_received(:deliver_now)
end
end
context 'with the notification being for an update journal' do
let(:journal_initial) { false }
it 'sends a mail' do
call
expect(UserMailer)
.to have_received(:wiki_page_updated)
.with(recipient,
journal.journable)
expect(mail)
.to have_received(:deliver_now)
end
end
context 'with the notification read in app already' do
let(:read_ian) { true }
it 'sends no mail' do
call
expect(UserMailer)
.not_to have_received(:wiki_page_added)
expect(UserMailer)
.not_to have_received(:wiki_page_updated)
end
end
end
context 'with a news journal notification' do
let(:journal) do
build_stubbed(:news_journal,
journable: build_stubbed(:news)).tap do |j|
allow(j)
.to receive(:initial?)
.and_return(journal_initial)
end
end
let(:notification) do
build_stubbed(:notification,
journal:,
recipient:,
actor:)
end
let(:mail) do
mail = instance_double(ActionMailer::MessageDelivery)
allow(UserMailer)
.to receive(:news_added)
.and_return(mail)
allow(mail)
.to receive(:deliver_now)
mail
end
let(:journal_initial) { false }
before do
mail
end
context 'with the notification being for an initial journal' do
let(:journal_initial) { true }
it 'sends a mail' do
call
expect(UserMailer)
.to have_received(:news_added)
.with(recipient,
journal.journable)
expect(mail)
.to have_received(:deliver_now)
end
end
# This case should not happen as no notification is created in this case that would
# trigger the NotificationJob. But as this might change, this test case is in place.
context 'with the notification being for an update journal' do
let(:journal_initial) { false }
it 'sends no mail' do
call
expect(UserMailer)
.not_to have_received(:news_added)
end
end
end
context 'with a message journal notification' do
let(:journal) do
build_stubbed(:message_journal,
journable: build_stubbed(:message))
end
let(:read_ian) { false }
let(:notification) do
build_stubbed(:notification,
journal:,
resource: journal.journable,
recipient:,
actor:,
read_ian:)
end
let(:mail) do
mail = instance_double(ActionMailer::MessageDelivery)
allow(UserMailer)
.to receive(:message_posted)
.and_return(mail)
allow(mail)
.to receive(:deliver_now)
mail
end
before do
mail
end
it 'sends a mail' do
call
expect(UserMailer)
.to have_received(:message_posted)
.with(recipient,
journal.journable)
expect(mail)
.to have_received(:deliver_now)
end
context 'with the notification read in app already' do
let(:read_ian) { true }
it 'sends no mail' do
call
expect(UserMailer)
.not_to have_received(:message_posted)
end
end
end
context 'with a different journal notification' do
let(:journal) do
build_stubbed(:journal,
journable: build_stubbed(:work_package))
end
let(:notification) do
build_stubbed(:notification,
journal:,
recipient:,
actor:)
end
# did that before
it 'does nothing' do
expect { call }
.not_to raise_error(ArgumentError)
end
it 'does not send a mail' do
expect { call }
.not_to change(ActionMailer::Base.deliveries, :count)
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 Notifications::CreateService < BaseServices::Create
protected
def persist(service_result)
super
rescue ActiveRecord::InvalidForeignKey
service_result.success = false
service_result.errors.add(:journal_id, :does_not_exist)
service_result
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 Notifications::CreateService, type: :model do
it_behaves_like 'BaseServices create service'
end
|
In the context of a Ruby programming project, there is a module named 'Dictionary'. This module is defined to have a class method called `table_name_prefix`. The purpose of this module seems to be to provide a prefix for database table names related to the Dictionary. In simpler terms, it's used in the Rails environment where Active Record automatically appends the name of the model to tables (i.e., "dictionary_users" rather than just "users") if the class method `table_name_prefix` is defined in a module named 'Dictionary'.
| module Dictionary
def self.table_name_prefix
'dictionary_'
end
end
|
In the context of this Ruby code, a standalone instruction would be:
"The Lock class represents a lock object for {CloudUser} and {Application}s that it owns. It has three read-only attributes `apps`, `user`, and `locked` representing the list of applications locked, the owner user, and whether the user is locked respectively. The class also includes Mongoid::Document which allows interaction with a MongoDB database.
The Lock class has two methods for creating or deleting locks on users: `create_lock(user)` and `delete_lock(user)`.
There are two other methods, `lock_user(user, app, timeout=1800)` and `unlock_user(user, app)` that attempt to lock or unlock a user respectively. These methods also check for existing locks on the same application owned by the same user before proceeding with the operation.
There are two additional methods, `lock_application(application, timeout=1800)` and `unlock_application(application)`, that attempt to lock or unlock an application respectively. These methods also retrieve the owner of the application from its domain before attempting to lock or unlock it."
Please note: The actual implementation details might be too complex for a standalone instruction as they involve Mongoid::Document interaction with a MongoDB database and object-oriented concepts in Ruby. However, this brief explanation should provide an understanding of what the code does.
| # Represents a lock object for a {CloudUser} and {Application}s that it owns
# @!attribute [r] apps
# @return List of {Application}s that are locked
# @!attribute [r] user
# @return {CloudUser} owner of the lock
# @!attribute [r] locked
# @return [Boolean] representing if the user is locked
class Lock
include Mongoid::Document
belongs_to :user, class_name: CloudUser.name
field :locked, type: Boolean, default: false
field :timeout, type: Integer, default: 0
field :app_ids, type: Hash, default: {}
index({:user_id => 1})
create_indexes
# Attempts to lock the {CloudUser}. Once locked, no other threads can obtain a lock on the {CloudUser} or any owned {Application}s.
# This lock is denied if any of the {Application}s owned by the {CloudUser} are currently locked.
#
# == Parameters:
# user::
# The {CloudUser} to attempt to lock
#
# == Returns:
# True if the lock was successful.
def self.create_lock(user)
lock = Lock.find_or_create_by( :user_id => user._id )
end
def self.delete_lock(user)
lock = Lock.delete( :user_id => user._id )
end
# Attempts to lock the {CloudUser}.
# NOTE: User lock is available only for user apps with application lock.
def self.lock_user(user, app, timeout=1800)
begin
now = Time.now.to_i
lock = Lock.find_or_create_by( :user_id => user._id )
query = {:user_id => user._id, "$or" => [{:locked => false}, {:timeout.lt => now}], "app_ids.#{app._id}" => { "$exists" => true }}
updates = {"$set" => { locked: true, timeout: (now + timeout) }}
lock = Lock.where(query).find_and_modify(updates, new: true)
return (not lock.nil?)
rescue Moped::Errors::OperationFailure
return false
end
end
# Attempts to unlock the {CloudUser}.
#
# == Parameters:
# user::
# The {CloudUser} to attempt to unlock
#
# == Returns:
# True if the unlock was successful.
def self.unlock_user(user, app)
begin
query = {:user_id => user._id, :locked => true, "app_ids.#{app._id}" => { "$exists" => true }}
updates = {"$set" => { "locked" => false }}
lock = Lock.where(query).find_and_modify(updates, new: true)
return (not lock.nil?)
rescue Moped::Errors::OperationFailure
return false
end
end
# Attempts to lock an {Application}. Once locked, no other threads can obtain a lock on the {Application} or the {CloudUser} that owns it.
# This lock is denied if the owning {CloudUser} is locked or the {Application} has been locked by another thread.
#
# == Parameters:
# application::
# The {Application} to attempt to lock
#
# == Returns:
# True if the lock was successful.
def self.lock_application(application, timeout=1800)
begin
# application.domain can be nil if the application is being created immediately after domain creation
# If the domain is being read from the secondary, it may not be present
# If domain is nil, try to load the domain from the primary
# Note: If there is a way to load the domain relationship from the primary, we should do that
if application.domain.nil?
user_id = Domain.find_by(_id: application.domain_id).owner_id
else
user_id = application.domain.owner_id
end
app_id = application._id.to_s
now = Time.now.to_i
query = { :user_id => user_id, "$or" => [{"app_ids.#{app_id}" => {"$exists" => false}}, {"app_ids.#{app_id}" => {"$lt" => now}}] }
updates = {"$set"=> { "app_ids.#{app_id}" => (now + timeout) }}
lock = Lock.where(query).find_and_modify(updates, new: true)
return (not lock.nil?)
rescue Moped::Errors::OperationFailure => ex
Rails.logger.error "Failed to obtain lock for application #{application.name}: #{ex.message}"
return false
end
end
# Attempts to unlock an {Application}.
#
# == Parameters:
# application::
# The {Application} to attempt to unlock
#
# == Returns:
# True if the unlock was successful.
def self.unlock_application(application)
begin
# application.domain can be nil if the application is being created immediately after domain creation
# If the domain is being read from the secondary, it may not be present
# If domain is nil, try to load the domain from the primary
# Note: If there is a way to load the domain relationship from the primary, we should do that
if application.domain.nil?
user_id = Domain.find_by(_id: application.domain_id).owner_id
else
user_id = application.domain.owner_id
end
app_id = application._id.to_s
query = {:user_id => user_id, "app_ids.#{app_id}" => { "$exists" => true }}
updates = {"$unset"=> {"app_ids.#{app_id}" => ""}}
lock = Lock.where(query).find_and_modify(updates, new: true)
return (not lock.nil?)
rescue Moped::Errors::OperationFailure => ex
Rails.logger.error "Failed to unlock application #{application.name}: #{ex.message}"
return false
end
end
end
|
In the context of this Ruby code snippet, we have a formula for Homebrew (a package manager for macOS) which is called 'Lean'. This formula is written in Ruby and it's designed to install Lean theorem prover on your Mac.
The tool, Lean, is a dependently typed programming language which supports constructing mathematics at the type level, and is especially suited for formalizing mathematical concepts along with their proofs (a form of computer proof). This formula was developed by contributors to the community around homepage 'https://leanprover-community.github.io/'.
The code snippet begins defining a Ruby class called `Lean`, which inherits from `Formula` provided by Homebrew. The class is designed to manage Lean's installation and upgrade process on your machine.
Here are some of the key attributes and methods used:
- desc "Theorem prover": This describes the purpose of this formula i.e., it is a theorem prover tool.
- homepage URL: It points to the official website of Lean where you can find more information about it.
- url "https://github.com/leanprover-community/lean/archive/v3.42.1.tar.gz": This is a link leading to the source code archive for version 3.42.1 of Lean.
- sha256: It is a SHA256 hash value generated from the source code archive, ensuring its integrity.
- license "Apache-2.0": This identifies the software's license as Apache 2.0.
- livecheck do...end: Lean formula uses 'livecheck' to check if there are any new versions of Lean available and updates them automatically.
- bottle do...end: It defines precompiled binaries for various platforms, making installation faster.
- depends_on "cmake" => :build, ...: This snippet lists all the dependencies that must be installed before Lean can run on your machine, including 'cmake' and others.
- conflicts_with...end: It ensures that there is no conflict between this formula and another called 'elan-init'.
- def install: The Ruby method for defining how to install the software package. Here it builds Lean from source code using CMake and installs it into Homebrew's prefix location by invoking a series of commands via system calls.
- test do...end: It provides an example of running some tests on this formula, proving that it correctly installed Lean.
Please note the Ruby syntax is used in this context. You should be familiar with Ruby to understand its usage within this context.
| class Lean < Formula
desc "Theorem prover"
homepage "https://leanprover-community.github.io/"
url "https://github.com/leanprover-community/lean/archive/v3.42.1.tar.gz"
sha256 "5b8cbfdea6cf4de5488467297958876aa0b3a79ed5806f7d0f01a0c396beb4e2"
license "Apache-2.0"
head "https://github.com/leanprover-community/lean.git", branch: "master"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
strategy :git do |tags, regex|
tags.map do |tag|
version = tag[regex, 1]
next if version == "9.9.9" # Omit a problematic version tag
version
end
end
end
bottle do
sha256 cellar: :any, arm64_monterey: "58337f99ae7f334d298267e4f0153334d408a72d7640aeb7834d6fc8499ed0ca"
sha256 cellar: :any, arm64_big_sur: "d8dfeaf7e902829013d0109938b910061349a2d16394e48c714a3a1f4b312717"
sha256 cellar: :any, monterey: "1e14e749b7b08576bc0dd91f6f6fec6ab97c1c32d79f22a69c5a6b4b41330f95"
sha256 cellar: :any, big_sur: "d623ba837328fe54810386ce2385aef9d147784bdf71c43fb749e09bf68546a0"
sha256 cellar: :any, catalina: "e16cb80f3a05541ac1d981ff75a6ade15a601931ed8dfa606076ff2b06ac67a9"
sha256 cellar: :any_skip_relocation, x86_64_linux: "4d8d848d08308e6301a5eb4ae8bf6f7155a0936df27270c6a82ba699737c3cca"
end
depends_on "cmake" => :build
depends_on "coreutils"
depends_on "gmp"
depends_on "jemalloc"
depends_on macos: :mojave
on_linux do
depends_on "gcc"
end
conflicts_with "elan-init", because: "`lean` and `elan-init` install the same binaries"
fails_with gcc: "5"
def install
args = std_cmake_args + %w[
-DCMAKE_CXX_FLAGS='-std=c++14'
]
system "cmake", "-S", "src", "-B", "src/build", *args
system "cmake", "--build", "src/build"
system "cmake", "--install", "src/build"
end
test do
(testpath/"hello.lean").write <<~EOS
def id' {α : Type} (x : α) : α := x
inductive tree (α : Type) : Type
| node : α → list tree → tree
example (a b : Prop) : a ∧ b -> b ∧ a :=
begin
intro h, cases h,
split, repeat { assumption }
end
EOS
system bin/"lean", testpath/"hello.lean"
system bin/"leanpkg", "help"
end
end
|
In the context of a Ruby on Rails project, there is a class named `ProjectFeature` that manages permissions for various features related to projects. This class has several properties and methods related to access levels, validation rules, default values, and feature availability based on user roles.
One important property in this class is the constant array 'FEATURES', which includes :issues, :merge_requests, :wiki, :snippets, :builds, :repository, and :pages. This lists all possible features that a project can have.
The `access_level` method returns the access level for a specified feature based on its associated attribute. For example, if we call `project.feature.access_level(:issues)`, it will return the current access level of issues for this project.
There are several validation methods that check the validity of these access levels against each other and repository-wide settings. One method is 'repository_children_level' which checks whether a feature’s visibility level isn’t higher than the repository’s visibility level.
The class also has `default_value_for` methods for setting default values for all features, except :pages. The access levels are set to ENABLED by default and `nil` is not allowed. This ensures that each feature will have a defined access level when initialized.
A method named 'feature_available?' checks if a certain feature is available to a given user based on their role in the project. It firstly, checks whether this feature is enabled for this particular user by checking the Feature flag. Then it verifies the user's permissions with `get_permission` helper function using the provided access level of that feature.
The class includes several methods to check if a certain feature (like :wiki, :builds etc.) is enabled or disabled based on their visibility levels in project settings.
Finally, there are 'public_pages?' method which checks if Pages feature for a given project can be accessed by public users. It considers the access level of the pages and whether the project itself is public.
These methods provide an interface to manage and validate features' visibility levels within a project. They ensure that only authorized individuals have access to certain features, ensuring data security and privacy in a collaborative environment like GitLab.
Remember this class is part of ActiveRecord::Base and therefore works with Active Record ORM (Object-Relational Mapping). It enables us to interact with the database via Ruby code by creating classes for each table we want to interact with, here it's ProjectFeature related to 'project_features' in the database.
| # frozen_string_literal: true
class ProjectFeature < ActiveRecord::Base
# == Project features permissions
#
# Grants access level to project tools
#
# Tools can be enabled only for users, everyone or disabled
# Access control is made only for non private projects
#
# levels:
#
# Disabled: not enabled for anyone
# Private: enabled only for team members
# Enabled: enabled for everyone able to access the project
# Public: enabled for everyone (only allowed for pages)
#
# Permission levels
DISABLED = 0
PRIVATE = 10
ENABLED = 20
PUBLIC = 30
FEATURES = %i(issues merge_requests wiki snippets builds repository pages).freeze
PRIVATE_FEATURES_MIN_ACCESS_LEVEL = { merge_requests: Gitlab::Access::REPORTER }.freeze
class << self
def access_level_attribute(feature)
feature = ensure_feature!(feature)
"#{feature}_access_level".to_sym
end
def quoted_access_level_column(feature)
attribute = connection.quote_column_name(access_level_attribute(feature))
table = connection.quote_table_name(table_name)
"#{table}.#{attribute}"
end
def required_minimum_access_level(feature)
feature = ensure_feature!(feature)
PRIVATE_FEATURES_MIN_ACCESS_LEVEL.fetch(feature, Gitlab::Access::GUEST)
end
private
def ensure_feature!(feature)
feature = feature.model_name.plural.to_sym if feature.respond_to?(:model_name)
raise ArgumentError, "invalid project feature: #{feature}" unless FEATURES.include?(feature)
feature
end
end
# Default scopes force us to unscope here since a service may need to check
# permissions for a project in pending_delete
# http://stackoverflow.com/questions/1540645/how-to-disable-default-scope-for-a-belongs-to
belongs_to :project, -> { unscope(where: :pending_delete) }
validates :project, presence: true
validate :repository_children_level
validate :allowed_access_levels
default_value_for :builds_access_level, value: ENABLED, allows_nil: false
default_value_for :issues_access_level, value: ENABLED, allows_nil: false
default_value_for :merge_requests_access_level, value: ENABLED, allows_nil: false
default_value_for :snippets_access_level, value: ENABLED, allows_nil: false
default_value_for :wiki_access_level, value: ENABLED, allows_nil: false
default_value_for :repository_access_level, value: ENABLED, allows_nil: false
def feature_available?(feature, user)
# This feature might not be behind a feature flag at all, so default to true
return false unless ::Feature.enabled?(feature, user, default_enabled: true)
get_permission(user, access_level(feature))
end
def access_level(feature)
public_send(ProjectFeature.access_level_attribute(feature)) # rubocop:disable GitlabSecurity/PublicSend
end
def builds_enabled?
builds_access_level > DISABLED
end
def wiki_enabled?
wiki_access_level > DISABLED
end
def merge_requests_enabled?
merge_requests_access_level > DISABLED
end
def issues_enabled?
issues_access_level > DISABLED
end
def pages_enabled?
pages_access_level > DISABLED
end
def public_pages?
return true unless Gitlab.config.pages.access_control
pages_access_level == PUBLIC || pages_access_level == ENABLED && project.public?
end
private
# Validates builds and merge requests access level
# which cannot be higher than repository access level
def repository_children_level
validator = lambda do |field|
level = public_send(field) || ProjectFeature::ENABLED # rubocop:disable GitlabSecurity/PublicSend
not_allowed = level > repository_access_level
self.errors.add(field, "cannot have higher visibility level than repository access level") if not_allowed
end
%i(merge_requests_access_level builds_access_level).each(&validator)
end
# Validates access level for other than pages cannot be PUBLIC
def allowed_access_levels
validator = lambda do |field|
level = public_send(field) || ProjectFeature::ENABLED # rubocop:disable GitlabSecurity/PublicSend
not_allowed = level > ProjectFeature::ENABLED
self.errors.add(field, "cannot have public visibility level") if not_allowed
end
(FEATURES - %i(pages)).each {|f| validator.call("#{f}_access_level")}
end
def get_permission(user, level)
case level
when DISABLED
false
when PRIVATE
user && (project.team.member?(user) || user.full_private_access?)
when ENABLED
true
when PUBLIC
true
else
true
end
end
end
|
In the context of a Ruby on Rails application testing, the code provided is for testing user model behavior. The tests are written using ActiveSupport::TestCase which comes with Rails and allows us to write test cases in an organized manner.
The 'setup' method creates a new instance variable `@user` with various attributes like name, email, password etc., that we use throughout the tests.
Following are few of the test cases:
1. The first test 'should be valid', asserts that when the user record is created and assigned values to its fields, it should be considered as a valid instance by the application's validation rules specified in User model.
2. In next two tests, we check if name and email are not left blank which is necessary for all users in database. If these are empty, then that user record should not be accepted/invalid.
3. Then there are test cases checking the validity of an email address format by providing various valid and invalid emails addresses.
4. Test 'password should be present (nonblank)' checks if a password field is left blank or contains only spaces. If it does, then user record shouldn't be considered as valid.
5. Lastly, test 'authenticated? should return false for a user with nil digest', verifies that the method `authenticated?` in User model returns false when provided an empty string, which is used to check if remember digest of a user is present or not.
| # frozen_string_literal: true
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: 'Example User', email: '[email protected]',
password: 'foobar', password_confirmation: 'foobar')
end
test 'should be valid' do
assert @user.valid?
end
test 'name should be present' do
@user.name = ' '
assert_not @user.valid?
end
test 'email should be present' do
@user.email = ' '
assert_not @user.valid?
end
test 'email validation should accept valid addresses' do
valid_addresses = %w[[email protected] [email protected] [email protected]
[email protected] [email protected]]
valid_addresses.each do |valid_address|
@user.email = valid_address
assert @user.valid?, "#{valid_address.inspect} should be valid"
end
end
test 'email validation should reject invalid addresses' do
invalid_addresses = %w[user@example,com user_at_foo.org user.name@example.
foo@bar_baz.com foo@bar+baz.com]
invalid_addresses.each do |invalid_address|
@user.email = invalid_address
assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
end
end
test 'email addresses should be unique' do
duplicate_user = @user.dup
@user.save
assert_not duplicate_user.valid?
end
test 'email addresses should be unique (case sensitive)' do
duplicate_user = @user.dup
duplicate_user.email = @user.email.upcase
@user.save
assert_not duplicate_user.valid?
end
test 'email addresses should be saved as lower-case' do
mixed_case_email = '[email protected]'
@user.email = mixed_case_email
@user.save
assert_equal mixed_case_email.downcase, @user.reload.email
end
test 'password should be present (nonblank)' do
@user.password = @user.password_confirmation = ' ' * 6
assert_not @user.valid?
end
test 'password should have a minimum length' do
@user.password = @user.password_confirmation = 'a' * 5
assert_not @user.valid?
end
test 'authenticated? should return false for a user with nil digest' do
assert_not @user.authenticated?('')
end
end
|
In the context of a Linux shell script, this code is setting up Kubernetes in Docker using DNS. The script checks for an environment variable `RUN_SKYDNS` which determines whether to run Skydns or not.
The 'if' condition sets the variable `DNS_ARGUMENTS` based on whether `RUN_SKYDNS` is set to "yes" or "no".
If `RUN_SKYDNS` equals "yes", it launches kube2sky and Skydns as Docker containers. These are running in the host network namespace, so they can communicate with each other on port 53 (the default DNS port). The scripts wait until Kubernetes is ready by checking if the localhost node can be found using `kubectl get nodes` command inside a loop and waiting for 5 seconds before trying again.
If `RUN_SKYDNS` equals "no", it runs an empty 'true' command to do nothing, effectively skipping launching kube2sky and Skydns.
At the end of the script, the working directory is reset back to its previous state by using the `cd ${PWD}` line. This ensures that subsequent commands run from this shell are not affected by the current script's execution.
Note: It's assumed that Docker and Kubernetes have been set up in the environment where this code is being executed, as the script uses a 'docker exec' command to interact with the hyperkube container which runs Kubernetes within a Docker container.
| #!/bin/bash
# Running skydns based on instructions at: https://testdatamanagement.wordpress.com/2015/09/01/running-kubernetes-in-docker-with-dns-on-a-single-node/
PWD=`pwd`
BASEDIR=`readlink -e $(dirname ${0})`
cd ${BASEDIR}
KUBECTL='docker exec hyperkube /hyperkube kubectl'
#RUN_SKYDNS="yes"
RUN_SKYDNS="no"
# DNS_ARGUMENTS needs to be passed when Kubernetes is setup.
if [ "${RUN_SKYDNS}" = "yes" ]; then
DNS_ARGUMENTS="--cluster-dns=10.0.0.10 --cluster-domain=cluster.local"
else
DNS_ARGUMENTS=""
fi
wait_until_k8s_ready() {
# Wait until kubernetes is up and fully responsive
while :
do
${KUBECTL} get nodes 2>/dev/null | grep -q '127.0.0.1'
if [ "${?}" = "0" ]; then
break
else
echo "sleeping for 5 seconds (waiting for kubernetes to start)"
sleep 5
fi
done
echo "kubernetes nodes:"
${KUBECTL} get nodes
}
if [ "${RUN_SKYDNS}" = "yes" ]; then
wait_until_k8s_ready
echo "Launch kube2sky..."
docker run -d --net=host gcr.io/google_containers/kube2sky:1.11 --kube_master_url=http://127.0.0.1:8080 --domain=cluster.local
echo ""
echo "Launch SkyDNS..."
docker run -d --net=host gcr.io/google_containers/skydns:2015-03-11-001 --machines=http://localhost:4001 --addr=0.0.0.0:53 --domain=cluster.local
else
true
fi
cd ${PWD}
|
In the context of a script that runs Kubernetes commands, this Ruby code does the following:
1. It is running a bash shell script which copies an existing kubeconfig file from `/etc/kubernetes/admin.conf` to `/root/kube-admin.conf` using the cp command with '-i' option for interactive confirmation before overwriting if the target file already exists.
2. After copying, it runs 'kubectl --kubeconfig /root/kube-admin.conf $*'. The '$*' is a special shell variable that represents all arguments passed to the script. It allows passing any number of options or commands to kubectl with no additional code required by the user.
| #!/bin/bash
# cp -i /etc/kubernetes/admin.conf /root/kube-admin.conf
kubectl --kubeconfig /root/kube-admin.conf $*
|
In the context of this given Ruby code, it is a script designed to run as an entrypoint for Docker containers. This means that whenever we start or run our container using this script, certain actions will be taken based on different scenarios.
Here's the key phrase from the code:
"$1" = "/opt/logstash/bin/logstash". In the context of shell scripting and Docker containers, "$1", "$2", etc., are variables that represent arguments passed to a script when it is invoked. Here, we're checking if the first argument (the command that was run) matches "/opt/logstash/bin/logstash". If so, then the code executes "/opt/logstash/bin/logstash agent -f /opt/logstash.conf". This sets up Logstash to process logs in accordance with the configuration file located at '/opt/conf/logstash.conf'.
If the first argument does not match "/opt/logstash/bin/logstash", then it executes whatever command was passed as an argument ("$@" represents all arguments). This is useful for allowing scripts to run different commands or actions depending on how they were invoked, providing a degree of flexibility.
| #!/bin/bash
set -e
if [ "$1" = "/opt/logstash/bin/logstash" ]; then
exec "$1" agent -f /opt/conf/logstash.conf
else
exec "$@"
fi |
In the context of a Ruby script, there are two functions defined:
1. The `seqWatch()` function is responsible for watching files named *.diag in the given directory (recursive) and generating corresponding PNG file when a change occurs. It takes an optional parameter which sets the folder to watch (defaulting to the current working directory if not specified). If no folder is provided, it prints a message setting the folder to the current working directory. The function uses inotifywait command line utility to monitor for changes on filesystem events and then executes seqdiag command-line utility as per file type being watched.
2. The `seqInit()` function is used to initialize a seqdiag file with preferences defined in seqdiag.init. It takes one parameter which sets the path of the file to be created (must provide an absolute path). If the directory for the new file does not exist, it creates the directories leading up to the filename. Then, it copies the seqdiag.init from a predefined location (TOOLING) to the newly created file.
| #---------#
# Seqdiag #
#---------#
# Watches for files named *.diag in the given directory (recursive) and generates the
# corresponding PNG file.
# $1: the folder to watch (Default: pwd)
# shellcheck disable=SC2034
seqWatch() {
local folder="$1"
[[ -n "$folder" ]] || {
printfc 'Folder not defined, it was set to pwd\n' "$YELLOW"
folder="$(pwd)";
}
inotifywait -rm "$folder" -e close_write |
while read path action file; do
if [[ "$file" =~ .*\.diag$ ]]; then
seqdiag "$path$file" --no-transparency -a
fi
done
}
# Inits a seqdiag file with the preferences defined in seqdiag.init.
# Uses: $TOOLING
# $1: the file to be created (absolute path)
seqInit() {
local filePath="${1?Missing path to file}"
mkdir -p "$(dirname "$filePath")"
cp "$TOOLING/bashrc/Utils/seqdiag.init" "$(basename "$filePath")"
}
|
In the context of Bash scripting, this code is removing all blank lines from clipboard content. The command `pbpaste` retrieves the contents copied to the system's pasteboard; then it uses `awk '!/^[ ]*$/'` to filter out empty lines; and finally, `pbcopy` stores these filtered lines back into the pasteboard.
The script is run in a terminal and requires user interaction by manually copying text into the clipboard before running the command (using pbpaste), performing some operation with that copied content, then copying it back to the clipboard again (using pbcopy). This workflow doesn't involve any specific Ruby code.
| #!/bin/bash
# Author: Eason Yi
# Date: 2017-05-17
pbpaste|awk '!/^[ ]*$/'|pbcopy|pbpaste
|
The given Ruby code contains data about time zone descriptions for different countries. It is a deprecated version, as the file has been replaced by zone1970.tab (see its comments). The first column of the file contains country codes, while the second contains coordinates and TZ columns contain information on corresponding time zones.
Each row stands for an area that is the intersection of a region identified by a country code and of a zone where civil clocks have agreed since 1970; this is a narrower definition than that of zone1970.tab. The data in this file is intended as a backward-compatibility aid for older programs, but new programs should use zone1970.tab instead.
The comments column provides additional information about the time zones represented by each row, including any deprecated version identifiers and other information on the status of implementation and testing of these timezones in various applications.
This table is intended as an aid for users, to help them select appropriate time zone data entries suitable for their practical needs. It should not be used to take or endorse any position on legal or territorial claims.
| # tz zone descriptions (deprecated version)
#
# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.
#
# From Paul Eggert (2014-07-31):
# This file is intended as a backward-compatibility aid for older programs.
# New programs should use zone1970.tab. This file is like zone1970.tab (see
# zone1970.tab's comments), but with the following additional restrictions:
#
# 1. This file contains only ASCII characters.
# 2. The first data column contains exactly one country code.
#
# Because of (2), each row stands for an area that is the intersection
# of a region identified by a country code and of a zone where civil
# clocks have agreed since 1970; this is a narrower definition than
# that of zone1970.tab.
#
# This table is intended as an aid for users, to help them select time
# zone data entries appropriate for their practical needs. It is not
# intended to take or endorse any position on legal or territorial claims.
#
#country-
#code coordinates TZ comments
AD +4230+00131 Europe/Andorra
AE +2518+05518 Asia/Dubai
AF +3431+06912 Asia/Kabul
AG +1703-06148 America/Antigua
AI +1812-06304 America/Anguilla
AL +4120+01950 Europe/Tirane
AM +4011+04430 Asia/Yerevan
AO -0848+01314 Africa/Luanda
AQ -7750+16636 Antarctica/McMurdo New Zealand time - McMurdo, South Pole
AQ -6617+11031 Antarctica/Casey Casey
AQ -6835+07758 Antarctica/Davis Davis
AQ -6640+14001 Antarctica/DumontDUrville Dumont-d'Urville
AQ -6736+06253 Antarctica/Mawson Mawson
AQ -6448-06406 Antarctica/Palmer Palmer
AQ -6734-06808 Antarctica/Rothera Rothera
AQ -690022+0393524 Antarctica/Syowa Syowa
AQ -720041+0023206 Antarctica/Troll Troll
AQ -7824+10654 Antarctica/Vostok Vostok
AR -3436-05827 America/Argentina/Buenos_Aires Buenos Aires (BA, CF)
AR -3124-06411 America/Argentina/Cordoba Argentina (most areas: CB, CC, CN, ER, FM, MN, SE, SF)
AR -2447-06525 America/Argentina/Salta Salta (SA, LP, NQ, RN)
AR -2411-06518 America/Argentina/Jujuy Jujuy (JY)
AR -2649-06513 America/Argentina/Tucuman Tucuman (TM)
AR -2828-06547 America/Argentina/Catamarca Catamarca (CT); Chubut (CH)
AR -2926-06651 America/Argentina/La_Rioja La Rioja (LR)
AR -3132-06831 America/Argentina/San_Juan San Juan (SJ)
AR -3253-06849 America/Argentina/Mendoza Mendoza (MZ)
AR -3319-06621 America/Argentina/San_Luis San Luis (SL)
AR -5138-06913 America/Argentina/Rio_Gallegos Santa Cruz (SC)
AR -5448-06818 America/Argentina/Ushuaia Tierra del Fuego (TF)
AS -1416-17042 Pacific/Pago_Pago
AT +4813+01620 Europe/Vienna
AU -3133+15905 Australia/Lord_Howe Lord Howe Island
AU -5430+15857 Antarctica/Macquarie Macquarie Island
AU -4253+14719 Australia/Hobart Tasmania (most areas)
AU -3956+14352 Australia/Currie Tasmania (King Island)
AU -3749+14458 Australia/Melbourne Victoria
AU -3352+15113 Australia/Sydney New South Wales (most areas)
AU -3157+14127 Australia/Broken_Hill New South Wales (Yancowinna)
AU -2728+15302 Australia/Brisbane Queensland (most areas)
AU -2016+14900 Australia/Lindeman Queensland (Whitsunday Islands)
AU -3455+13835 Australia/Adelaide South Australia
AU -1228+13050 Australia/Darwin Northern Territory
AU -3157+11551 Australia/Perth Western Australia (most areas)
AU -3143+12852 Australia/Eucla Western Australia (Eucla)
AW +1230-06958 America/Aruba
AX +6006+01957 Europe/Mariehamn
AZ +4023+04951 Asia/Baku
BA +4352+01825 Europe/Sarajevo
BB +1306-05937 America/Barbados
BD +2343+09025 Asia/Dhaka
BE +5050+00420 Europe/Brussels
BF +1222-00131 Africa/Ouagadougou
BG +4241+02319 Europe/Sofia
BH +2623+05035 Asia/Bahrain
BI -0323+02922 Africa/Bujumbura
BJ +0629+00237 Africa/Porto-Novo
BL +1753-06251 America/St_Barthelemy
BM +3217-06446 Atlantic/Bermuda
BN +0456+11455 Asia/Brunei
BO -1630-06809 America/La_Paz
BQ +120903-0681636 America/Kralendijk
BR -0351-03225 America/Noronha Atlantic islands
BR -0127-04829 America/Belem Para (east); Amapa
BR -0343-03830 America/Fortaleza Brazil (northeast: MA, PI, CE, RN, PB)
BR -0803-03454 America/Recife Pernambuco
BR -0712-04812 America/Araguaina Tocantins
BR -0940-03543 America/Maceio Alagoas, Sergipe
BR -1259-03831 America/Bahia Bahia
BR -2332-04637 America/Sao_Paulo Brazil (southeast: GO, DF, MG, ES, RJ, SP, PR, SC, RS)
BR -2027-05437 America/Campo_Grande Mato Grosso do Sul
BR -1535-05605 America/Cuiaba Mato Grosso
BR -0226-05452 America/Santarem Para (west)
BR -0846-06354 America/Porto_Velho Rondonia
BR +0249-06040 America/Boa_Vista Roraima
BR -0308-06001 America/Manaus Amazonas (east)
BR -0640-06952 America/Eirunepe Amazonas (west)
BR -0958-06748 America/Rio_Branco Acre
BS +2505-07721 America/Nassau
BT +2728+08939 Asia/Thimphu
BW -2439+02555 Africa/Gaborone
BY +5354+02734 Europe/Minsk
BZ +1730-08812 America/Belize
CA +4734-05243 America/St_Johns Newfoundland; Labrador (southeast)
CA +4439-06336 America/Halifax Atlantic - NS (most areas); PE
CA +4612-05957 America/Glace_Bay Atlantic - NS (Cape Breton)
CA +4606-06447 America/Moncton Atlantic - New Brunswick
CA +5320-06025 America/Goose_Bay Atlantic - Labrador (most areas)
CA +5125-05707 America/Blanc-Sablon AST - QC (Lower North Shore)
CA +4339-07923 America/Toronto Eastern - ON, QC (most areas)
CA +4901-08816 America/Nipigon Eastern - ON, QC (no DST 1967-73)
CA +4823-08915 America/Thunder_Bay Eastern - ON (Thunder Bay)
CA +6344-06828 America/Iqaluit Eastern - NU (most east areas)
CA +6608-06544 America/Pangnirtung Eastern - NU (Pangnirtung)
CA +484531-0913718 America/Atikokan EST - ON (Atikokan); NU (Coral H)
CA +4953-09709 America/Winnipeg Central - ON (west); Manitoba
CA +4843-09434 America/Rainy_River Central - ON (Rainy R, Ft Frances)
CA +744144-0944945 America/Resolute Central - NU (Resolute)
CA +624900-0920459 America/Rankin_Inlet Central - NU (central)
CA +5024-10439 America/Regina CST - SK (most areas)
CA +5017-10750 America/Swift_Current CST - SK (midwest)
CA +5333-11328 America/Edmonton Mountain - AB; BC (E); SK (W)
CA +690650-1050310 America/Cambridge_Bay Mountain - NU (west)
CA +6227-11421 America/Yellowknife Mountain - NT (central)
CA +682059-1334300 America/Inuvik Mountain - NT (west)
CA +4906-11631 America/Creston MST - BC (Creston)
CA +5946-12014 America/Dawson_Creek MST - BC (Dawson Cr, Ft St John)
CA +5848-12242 America/Fort_Nelson MST - BC (Ft Nelson)
CA +4916-12307 America/Vancouver Pacific - BC (most areas)
CA +6043-13503 America/Whitehorse Pacific - Yukon (south)
CA +6404-13925 America/Dawson Pacific - Yukon (north)
CC -1210+09655 Indian/Cocos
CD -0418+01518 Africa/Kinshasa Dem. Rep. of Congo (west)
CD -1140+02728 Africa/Lubumbashi Dem. Rep. of Congo (east)
CF +0422+01835 Africa/Bangui
CG -0416+01517 Africa/Brazzaville
CH +4723+00832 Europe/Zurich
CI +0519-00402 Africa/Abidjan
CK -2114-15946 Pacific/Rarotonga
CL -3327-07040 America/Santiago Chile (most areas)
CL -2709-10926 Pacific/Easter Easter Island
CM +0403+00942 Africa/Douala
CN +3114+12128 Asia/Shanghai Beijing Time
CN +4348+08735 Asia/Urumqi Xinjiang Time
CO +0436-07405 America/Bogota
CR +0956-08405 America/Costa_Rica
CU +2308-08222 America/Havana
CV +1455-02331 Atlantic/Cape_Verde
CW +1211-06900 America/Curacao
CX -1025+10543 Indian/Christmas
CY +3510+03322 Asia/Nicosia
CZ +5005+01426 Europe/Prague
DE +5230+01322 Europe/Berlin Germany (most areas)
DE +4742+00841 Europe/Busingen Busingen
DJ +1136+04309 Africa/Djibouti
DK +5540+01235 Europe/Copenhagen
DM +1518-06124 America/Dominica
DO +1828-06954 America/Santo_Domingo
DZ +3647+00303 Africa/Algiers
EC -0210-07950 America/Guayaquil Ecuador (mainland)
EC -0054-08936 Pacific/Galapagos Galapagos Islands
EE +5925+02445 Europe/Tallinn
EG +3003+03115 Africa/Cairo
EH +2709-01312 Africa/El_Aaiun
ER +1520+03853 Africa/Asmara
ES +4024-00341 Europe/Madrid Spain (mainland)
ES +3553-00519 Africa/Ceuta Ceuta, Melilla
ES +2806-01524 Atlantic/Canary Canary Islands
ET +0902+03842 Africa/Addis_Ababa
FI +6010+02458 Europe/Helsinki
FJ -1808+17825 Pacific/Fiji
FK -5142-05751 Atlantic/Stanley
FM +0725+15147 Pacific/Chuuk Chuuk/Truk, Yap
FM +0658+15813 Pacific/Pohnpei Pohnpei/Ponape
FM +0519+16259 Pacific/Kosrae Kosrae
FO +6201-00646 Atlantic/Faroe
FR +4852+00220 Europe/Paris
GA +0023+00927 Africa/Libreville
GB +513030-0000731 Europe/London
GD +1203-06145 America/Grenada
GE +4143+04449 Asia/Tbilisi
GF +0456-05220 America/Cayenne
GG +4927-00232 Europe/Guernsey
GH +0533-00013 Africa/Accra
GI +3608-00521 Europe/Gibraltar
GL +6411-05144 America/Godthab Greenland (most areas)
GL +7646-01840 America/Danmarkshavn National Park (east coast)
GL +7029-02158 America/Scoresbysund Scoresbysund/Ittoqqortoormiit
GL +7634-06847 America/Thule Thule/Pituffik
GM +1328-01639 Africa/Banjul
GN +0931-01343 Africa/Conakry
GP +1614-06132 America/Guadeloupe
GQ +0345+00847 Africa/Malabo
GR +3758+02343 Europe/Athens
GS -5416-03632 Atlantic/South_Georgia
GT +1438-09031 America/Guatemala
GU +1328+14445 Pacific/Guam
GW +1151-01535 Africa/Bissau
GY +0648-05810 America/Guyana
HK +2217+11409 Asia/Hong_Kong
HN +1406-08713 America/Tegucigalpa
HR +4548+01558 Europe/Zagreb
HT +1832-07220 America/Port-au-Prince
HU +4730+01905 Europe/Budapest
ID -0610+10648 Asia/Jakarta Java, Sumatra
ID -0002+10920 Asia/Pontianak Borneo (west, central)
ID -0507+11924 Asia/Makassar Borneo (east, south); Sulawesi/Celebes, Bali, Nusa Tengarra; Timor (west)
ID -0232+14042 Asia/Jayapura New Guinea (West Papua / Irian Jaya); Malukus/Moluccas
IE +5320-00615 Europe/Dublin
IL +314650+0351326 Asia/Jerusalem
IM +5409-00428 Europe/Isle_of_Man
IN +2232+08822 Asia/Kolkata
IO -0720+07225 Indian/Chagos
IQ +3321+04425 Asia/Baghdad
IR +3540+05126 Asia/Tehran
IS +6409-02151 Atlantic/Reykjavik
IT +4154+01229 Europe/Rome
JE +4912-00207 Europe/Jersey
JM +175805-0764736 America/Jamaica
JO +3157+03556 Asia/Amman
JP +353916+1394441 Asia/Tokyo
KE -0117+03649 Africa/Nairobi
KG +4254+07436 Asia/Bishkek
KH +1133+10455 Asia/Phnom_Penh
KI +0125+17300 Pacific/Tarawa Gilbert Islands
KI -0308-17105 Pacific/Enderbury Phoenix Islands
KI +0152-15720 Pacific/Kiritimati Line Islands
KM -1141+04316 Indian/Comoro
KN +1718-06243 America/St_Kitts
KP +3901+12545 Asia/Pyongyang
KR +3733+12658 Asia/Seoul
KW +2920+04759 Asia/Kuwait
KY +1918-08123 America/Cayman
KZ +4315+07657 Asia/Almaty Kazakhstan (most areas)
KZ +4448+06528 Asia/Qyzylorda Qyzylorda/Kyzylorda/Kzyl-Orda
KZ +5017+05710 Asia/Aqtobe Aqtobe/Aktobe
KZ +4431+05016 Asia/Aqtau Atyrau/Atirau/Gur'yev, Mangghystau/Mankistau
KZ +5113+05121 Asia/Oral West Kazakhstan
LA +1758+10236 Asia/Vientiane
LB +3353+03530 Asia/Beirut
LC +1401-06100 America/St_Lucia
LI +4709+00931 Europe/Vaduz
LK +0656+07951 Asia/Colombo
LR +0618-01047 Africa/Monrovia
LS -2928+02730 Africa/Maseru
LT +5441+02519 Europe/Vilnius
LU +4936+00609 Europe/Luxembourg
LV +5657+02406 Europe/Riga
LY +3254+01311 Africa/Tripoli
MA +3339-00735 Africa/Casablanca
MC +4342+00723 Europe/Monaco
MD +4700+02850 Europe/Chisinau
ME +4226+01916 Europe/Podgorica
MF +1804-06305 America/Marigot
MG -1855+04731 Indian/Antananarivo
MH +0709+17112 Pacific/Majuro Marshall Islands (most areas)
MH +0905+16720 Pacific/Kwajalein Kwajalein
MK +4159+02126 Europe/Skopje
ML +1239-00800 Africa/Bamako
MM +1647+09610 Asia/Rangoon
MN +4755+10653 Asia/Ulaanbaatar Mongolia (most areas)
MN +4801+09139 Asia/Hovd Bayan-Olgiy, Govi-Altai, Hovd, Uvs, Zavkhan
MN +4804+11430 Asia/Choibalsan Dornod, Sukhbaatar
MO +2214+11335 Asia/Macau
MP +1512+14545 Pacific/Saipan
MQ +1436-06105 America/Martinique
MR +1806-01557 Africa/Nouakchott
MS +1643-06213 America/Montserrat
MT +3554+01431 Europe/Malta
MU -2010+05730 Indian/Mauritius
MV +0410+07330 Indian/Maldives
MW -1547+03500 Africa/Blantyre
MX +1924-09909 America/Mexico_City Central Time
MX +2105-08646 America/Cancun Eastern Standard Time - Quintana Roo
MX +2058-08937 America/Merida Central Time - Campeche, Yucatan
MX +2540-10019 America/Monterrey Central Time - Durango; Coahuila, Nuevo Leon, Tamaulipas (most areas)
MX +2550-09730 America/Matamoros Central Time US - Coahuila, Nuevo Leon, Tamaulipas (US border)
MX +2313-10625 America/Mazatlan Mountain Time - Baja California Sur, Nayarit, Sinaloa
MX +2838-10605 America/Chihuahua Mountain Time - Chihuahua (most areas)
MX +2934-10425 America/Ojinaga Mountain Time US - Chihuahua (US border)
MX +2904-11058 America/Hermosillo Mountain Standard Time - Sonora
MX +3232-11701 America/Tijuana Pacific Time US - Baja California
MX +2048-10515 America/Bahia_Banderas Central Time - Bahia de Banderas
MY +0310+10142 Asia/Kuala_Lumpur Malaysia (peninsula)
MY +0133+11020 Asia/Kuching Sabah, Sarawak
MZ -2558+03235 Africa/Maputo
NA -2234+01706 Africa/Windhoek
NC -2216+16627 Pacific/Noumea
NE +1331+00207 Africa/Niamey
NF -2903+16758 Pacific/Norfolk
NG +0627+00324 Africa/Lagos
NI +1209-08617 America/Managua
NL +5222+00454 Europe/Amsterdam
NO +5955+01045 Europe/Oslo
NP +2743+08519 Asia/Kathmandu
NR -0031+16655 Pacific/Nauru
NU -1901-16955 Pacific/Niue
NZ -3652+17446 Pacific/Auckland New Zealand (most areas)
NZ -4357-17633 Pacific/Chatham Chatham Islands
OM +2336+05835 Asia/Muscat
PA +0858-07932 America/Panama
PE -1203-07703 America/Lima
PF -1732-14934 Pacific/Tahiti Society Islands
PF -0900-13930 Pacific/Marquesas Marquesas Islands
PF -2308-13457 Pacific/Gambier Gambier Islands
PG -0930+14710 Pacific/Port_Moresby Papua New Guinea (most areas)
PG -0613+15534 Pacific/Bougainville Bougainville
PH +1435+12100 Asia/Manila
PK +2452+06703 Asia/Karachi
PL +5215+02100 Europe/Warsaw
PM +4703-05620 America/Miquelon
PN -2504-13005 Pacific/Pitcairn
PR +182806-0660622 America/Puerto_Rico
PS +3130+03428 Asia/Gaza Gaza Strip
PS +313200+0350542 Asia/Hebron West Bank
PT +3843-00908 Europe/Lisbon Portugal (mainland)
PT +3238-01654 Atlantic/Madeira Madeira Islands
PT +3744-02540 Atlantic/Azores Azores
PW +0720+13429 Pacific/Palau
PY -2516-05740 America/Asuncion
QA +2517+05132 Asia/Qatar
RE -2052+05528 Indian/Reunion
RO +4426+02606 Europe/Bucharest
RS +4450+02030 Europe/Belgrade
RU +5443+02030 Europe/Kaliningrad MSK-01 - Kaliningrad
RU +554521+0373704 Europe/Moscow MSK+00 - Moscow area
RU +4457+03406 Europe/Simferopol MSK+00 - Crimea
RU +4844+04425 Europe/Volgograd MSK+00 - Volgograd, Kirov, Saratov
RU +4621+04803 Europe/Astrakhan MSK+01 - Astrakhan
RU +5312+05009 Europe/Samara MSK+01 - Samara, Udmurtia
RU +5420+04824 Europe/Ulyanovsk MSK+01 - Ulyanovsk
RU +5651+06036 Asia/Yekaterinburg MSK+02 - Urals
RU +5500+07324 Asia/Omsk MSK+03 - Omsk
RU +5502+08255 Asia/Novosibirsk MSK+03 - Novosibirsk, Tomsk
RU +5322+08345 Asia/Barnaul MSK+04 - Altai
RU +5345+08707 Asia/Novokuznetsk MSK+04 - Kemerovo
RU +5601+09250 Asia/Krasnoyarsk MSK+04 - Krasnoyarsk area
RU +5216+10420 Asia/Irkutsk MSK+05 - Irkutsk, Buryatia
RU +5203+11328 Asia/Chita MSK+05 - Zabaykalsky
RU +6200+12940 Asia/Yakutsk MSK+06 - Lena River
RU +623923+1353314 Asia/Khandyga MSK+06 - Tomponsky, Ust-Maysky
RU +4310+13156 Asia/Vladivostok MSK+07 - Amur River
RU +4658+14242 Asia/Sakhalin MSK+07 - Sakhalin Island
RU +643337+1431336 Asia/Ust-Nera MSK+07 - Oymyakonsky
RU +5934+15048 Asia/Magadan MSK+07 - Magadan
RU +6728+15343 Asia/Srednekolymsk MSK+08 - Sakha (E); North Kuril Is
RU +5301+15839 Asia/Kamchatka MSK+09 - Kamchatka
RU +6445+17729 Asia/Anadyr MSK+09 - Bering Sea
RW -0157+03004 Africa/Kigali
SA +2438+04643 Asia/Riyadh
SB -0932+16012 Pacific/Guadalcanal
SC -0440+05528 Indian/Mahe
SD +1536+03232 Africa/Khartoum
SE +5920+01803 Europe/Stockholm
SG +0117+10351 Asia/Singapore
SH -1555-00542 Atlantic/St_Helena
SI +4603+01431 Europe/Ljubljana
SJ +7800+01600 Arctic/Longyearbyen
SK +4809+01707 Europe/Bratislava
SL +0830-01315 Africa/Freetown
SM +4355+01228 Europe/San_Marino
SN +1440-01726 Africa/Dakar
SO +0204+04522 Africa/Mogadishu
SR +0550-05510 America/Paramaribo
SS +0451+03136 Africa/Juba
ST +0020+00644 Africa/Sao_Tome
SV +1342-08912 America/El_Salvador
SX +180305-0630250 America/Lower_Princes
SY +3330+03618 Asia/Damascus
SZ -2618+03106 Africa/Mbabane
TC +2128-07108 America/Grand_Turk
TD +1207+01503 Africa/Ndjamena
TF -492110+0701303 Indian/Kerguelen
TG +0608+00113 Africa/Lome
TH +1345+10031 Asia/Bangkok
TJ +3835+06848 Asia/Dushanbe
TK -0922-17114 Pacific/Fakaofo
TL -0833+12535 Asia/Dili
TM +3757+05823 Asia/Ashgabat
TN +3648+01011 Africa/Tunis
TO -2110-17510 Pacific/Tongatapu
TR +4101+02858 Europe/Istanbul
TT +1039-06131 America/Port_of_Spain
TV -0831+17913 Pacific/Funafuti
TW +2503+12130 Asia/Taipei
TZ -0648+03917 Africa/Dar_es_Salaam
UA +5026+03031 Europe/Kiev Ukraine (most areas)
UA +4837+02218 Europe/Uzhgorod Ruthenia
UA +4750+03510 Europe/Zaporozhye Zaporozh'ye/Zaporizhia; Lugansk/Luhansk (east)
UG +0019+03225 Africa/Kampala
UM +1645-16931 Pacific/Johnston Johnston Atoll
UM +2813-17722 Pacific/Midway Midway Islands
UM +1917+16637 Pacific/Wake Wake Island
US +404251-0740023 America/New_York Eastern (most areas)
US +421953-0830245 America/Detroit Eastern - MI (most areas)
US +381515-0854534 America/Kentucky/Louisville Eastern - KY (Louisville area)
US +364947-0845057 America/Kentucky/Monticello Eastern - KY (Wayne)
US +394606-0860929 America/Indiana/Indianapolis Eastern - IN (most areas)
US +384038-0873143 America/Indiana/Vincennes Eastern - IN (Da, Du, K, Mn)
US +410305-0863611 America/Indiana/Winamac Eastern - IN (Pulaski)
US +382232-0862041 America/Indiana/Marengo Eastern - IN (Crawford)
US +382931-0871643 America/Indiana/Petersburg Eastern - IN (Pike)
US +384452-0850402 America/Indiana/Vevay Eastern - IN (Switzerland)
US +415100-0873900 America/Chicago Central (most areas)
US +375711-0864541 America/Indiana/Tell_City Central - IN (Perry)
US +411745-0863730 America/Indiana/Knox Central - IN (Starke)
US +450628-0873651 America/Menominee Central - MI (Wisconsin border)
US +470659-1011757 America/North_Dakota/Center Central - ND (Oliver)
US +465042-1012439 America/North_Dakota/New_Salem Central - ND (Morton rural)
US +471551-1014640 America/North_Dakota/Beulah Central - ND (Mercer)
US +394421-1045903 America/Denver Mountain (most areas)
US +433649-1161209 America/Boise Mountain - ID (south); OR (east)
US +332654-1120424 America/Phoenix MST - Arizona (except Navajo)
US +340308-1181434 America/Los_Angeles Pacific
US +611305-1495401 America/Anchorage Alaska (most areas)
US +581807-1342511 America/Juneau Alaska - Juneau area
US +571035-1351807 America/Sitka Alaska - Sitka area
US +550737-1313435 America/Metlakatla Alaska - Annette Island
US +593249-1394338 America/Yakutat Alaska - Yakutat
US +643004-1652423 America/Nome Alaska (west)
US +515248-1763929 America/Adak Aleutian Islands
US +211825-1575130 Pacific/Honolulu Hawaii
UY -3453-05611 America/Montevideo
UZ +3940+06648 Asia/Samarkand Uzbekistan (west)
UZ +4120+06918 Asia/Tashkent Uzbekistan (east)
VA +415408+0122711 Europe/Vatican
VC +1309-06114 America/St_Vincent
VE +1030-06656 America/Caracas
VG +1827-06437 America/Tortola
VI +1821-06456 America/St_Thomas
VN +1045+10640 Asia/Ho_Chi_Minh
VU -1740+16825 Pacific/Efate
WF -1318-17610 Pacific/Wallis
WS -1350-17144 Pacific/Apia
YE +1245+04512 Asia/Aden
YT -1247+04514 Indian/Mayotte
ZA -2615+02800 Africa/Johannesburg
ZM -1525+02817 Africa/Lusaka
ZW -1750+03103 Africa/Harare
|
Instruction:
In the context of a data analysis project, you are using SQL to query and manipulate data. You need to analyze order quantities based on their lead time. You have two queries - one for orders with quantity 360 and another for orders with quantity 361. These queries join two tables from your WideWorldImportersDW database: 'Fact.Order' and 'Dimension.Stock Item'. The '[Fact].[Order]' table includes information about each order, while the '[Dimension].[Stock Item]' provides details about stock items in these orders.
The first query retrieves the [Order Key], [Lead Time Days], and [Quantity] from rows where the [Quantity] is 360. This is done by using an INNER JOIN to combine rows based on matching 'Stock Item Key's between both tables, and then filtering for orders with quantity 360.
The second query does the same but filters for orders with a quantity of 361 instead.
Remember that these queries are parameterized using SQL stored procedures (sp_executesql). The parameters @param1 are set to values of 360 and 361 respectively, controlling which data is returned by each query. This ensures the reusability of the code for different quantities without having to rewrite or modify it directly.
| USE [WideWorldImportersDW]
GO
ALTER DATABASE CURRENT SET COMPATIBILITY_LEVEL = 140
GO
EXEC sp_executesql
N'SELECT [fo].[Order Key], [si].[Lead Time Days], [fo].[Quantity]
FROM [Fact].[Order] AS [fo]
INNER JOIN [Dimension].[Stock Item] AS [si]
ON [fo].[Stock Item Key] = [si].[Stock Item Key]
WHERE [fo].[Quantity] =@param1',
N'@param1 int',
@param1 = 360
GO
EXEC sp_executesql
N'SELECT [fo].[Order Key], [si].[Lead Time Days], [fo].[Quantity]
FROM [Fact].[Order] AS [fo]
INNER JOIN [Dimension].[Stock Item] AS [si]
ON [fo].[Stock Item Key] = [si].[Stock Item Key]
WHERE [fo].[Quantity] =@param1',
N'@param1 int',
@param1 = 361
GO
|
In the context of setting up a database schema for storing plugin-specific key-value pairs, you would run these SQL commands.
The first command creates a table named 'pluginkeyvaluestore' if it doesn't already exist. This table has three columns: 'pluginid', 'pkey', and 'pvalue'. All of them are set to be VARCHAR type with specific lengths, 'pluginid' is limited to 190 characters, while 'pkey' is restricted to a maximum length of 50 characters. The column 'pvalue' can hold binary data represented by bytea type. The combination of the two first columns ('pluginid', and 'pkey') forms the primary key for this table.
The second command alters the 'pluginkeyvaluestore' table to add a new column named 'expireat'. If it doesn't exist already, this new column is set as bigint type with a default value of 0. This would be used to store the expiry time for each key-value pair in some sort of timestamp format (bigint being understood as number of milliseconds since Unix epoch).
The third block of code checks if the 'expireat' column has its default set to 0. If it does, it alters this default value to be NULL instead, indicating that keys do not expire by default. The condition is checked with a DO $$BEGIN...END statement wrapped around, which ensures that this logic only runs once and in the absence of any errors.
| CREATE TABLE IF NOT EXISTS pluginkeyvaluestore (
pluginid VARCHAR(190) NOT NULL,
pkey VARCHAR(50) NOT NULL,
pvalue bytea,
PRIMARY KEY (pluginid, pkey)
);
ALTER TABLE pluginkeyvaluestore ADD COLUMN IF NOT EXISTS expireat bigint DEFAULT 0;
DO $$BEGIN
IF (
SELECT column_default::bigint
FROM information_schema.columns
WHERE table_schema='public'
AND table_name='pluginkeyvaluestore'
AND column_name='expireat'
) = 0 THEN
ALTER TABLE pluginkeyvaluestore ALTER COLUMN expireat SET DEFAULT NULL;
END IF;
END$$;
|
In the context of a MySQL database, this SQL script is establishing a table called `datos personales`. This table contains information about individuals and their related data in fields such as first name (`nom`), last names (`pri_ape` and `seg_ape`), CURP (Colombian Unified Register of Population), group (`grup`), shift (`turno`), school name (`nom_esc`), and a code for the educational institution (`cct`). The database engine used is InnoDB, which supports transactions, row-level locking, and foreign key support.
| -- phpMyAdmin SQL Dump
-- version 4.6.5.2
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 08-11-2017 a las 23:42:52
-- Versión del servidor: 10.1.21-MariaDB
-- Versión de PHP: 5.6.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `cartilla_educacion`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `Datos personales`
--
CREATE TABLE `datos personales` (
`pri_ape` varchar(24) NOT NULL,
`seg_ape` varchar(24) NOT NULL,
`nom` varchar(35) NOT NULL,
`curp` varchar(18) NOT NULL,
`grup` varchar(10) NOT NULL,
`turno` varchar(15) NOT NULL,
`nom_esc` varchar(60) NOT NULL,
`cct` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
In the context of a database schema, this SQL code represents a stored procedure named "spCustomers_GetAll". This procedure is designed to retrieve all records from the 'Customers' table in the database.
Here's what each part does:
1. The keyword `CREATE PROCEDURE` tells SQL Server we are creating a new stored procedure.
2. `[dbo].[spCustomers_GetAll]` is the name of our new stored procedure. Here 'dbo' represents the default schema in your database and 'spCustomers_GetAll' is the name of the procedure.
3. The keyword `AS` signals the start of a block of code that will be run when this stored procedure is called.
4. Inside this block, we have one command: `BEGIN...END` which contains two commands - SET NOCOUNT ON and SELECT statement.
5. `SET NOCOUNT ON;` tells SQL Server to suppress messages like '(1 row affected)', which are not useful when creating stored procedures.
6. The final line is the SELECT query that fetches all fields from the table Customers. It specifically pulls out [CustomerId], [FirstName], [LastName] etc., assuming these columns exist in your database schema.
Note: Without knowing more about the rest of your SQL script, it's hard to provide a full understanding. This instruction is based on this snippet provided.
| CREATE PROCEDURE [dbo].[spCustomers_GetAll]
AS
BEGIN
SET NOCOUNT ON;
SELECT [CustomerId], [FirstName], [LastName], [FullName], [Address], [Phone], [Email], [PayCentreId], [UploadReceipts]
FROM [dbo].[Customers]
END
|
In the context of this Ruby code, there are several classes defined.
1. The `Status` class is used to parse a specific HTML page on a networked device, likely an access point in a Wi-Fi network controlled by OpenWRT. It looks for specific divs containing information about wireless networks (WLAN) and routing tables. This data is then processed into instances of the `WLAN_Config` class.
2. The `Table_Iter` base class provides an iterator method, `table_iter()`, which returns rows from a table in the parsed HTML as sequences of text. It's used by two subclasses: `OLSR_Connections` and `OLSR_Routes`, that parse specific tables on those pages into dictionaries.
3. The `OLSR_Connections` class parses the OLSR (Optimized Link State Routing) connections table for each neighbor and their quality of service data.
4. The `OLSR_Routes` class parses the routes information to identify which interface a gateway belongs to, which is used in the OpenWRT network setup.
5. Finally, the `OpenWRT` class initializes an instance with a site (server address) and a request dictionary. It uses these to populate the request with parsed data about interfaces and IP addresses from those pages. This data includes information about the device's version and any wireless networks it is connected to.
Each of these classes has its own methods that are used to parse specific sections of the HTML page into Python objects, making this Ruby code useful for network administration tasks.
| #!/usr/bin/python
# -*- coding: utf-8 -*-
# #*** <License> ************************************************************#
# This module is part of the repository CNDB.
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# #*** </License> ***********************************************************#
from _TFL.pyk import pyk
from rsclib.HTML_Parse import tag, Page_Tree
from rsclib.autosuper import autosuper
from spider.common import Interface, Inet4, Inet6, unroutable
from spider.common import WLAN_Config
from spider.luci import Version_Mixin
class Status (Page_Tree, Version_Mixin) :
url = 'cgi-bin/luci/freifunk/status/status'
retries = 2
timeout = 10
html_charset = 'utf-8' # force utf-8 encoding
wl_names = dict \
( ssid = 'ssid'
, _bsiid = 'bssid'
, channel = 'channel'
, mode = 'mode'
)
def parse (self) :
root = self.tree.getroot ()
self.wlans = []
self.routes = {}
for div in root.findall (".//%s" % tag ("div")) :
id = div.get ('id')
if id == 'cbi-wireless' :
wlan_div = div
elif id == 'cbi-routes' :
route_div = div
self.try_get_version (div)
for d in self.tbl_iter (wlan_div) :
for k, newkey in pyk.iteritems (self.wl_names) :
if k in d :
d [newkey] = d [k]
wl = WLAN_Config (** d)
self.wlans.append (wl)
for d in self.tbl_iter (route_div) :
iface = d.get ('iface')
gw = d.get ('gateway')
if iface and gw :
self.routes [iface] = gw
self.set_version (root)
# end def parse
def tbl_iter (self, div) :
tbl = div.find (".//%s" % tag ("table"))
assert tbl.get ('class') == 'cbi-section-table'
d = {}
for tr in tbl :
if 'cbi-section-table-row' not in tr.get ('class').split () :
continue
for input in tr.findall (".//%s" % tag ('input')) :
name = input.get ('id').split ('.') [-1]
val = input.get ('value')
d [name] = val
if not d :
continue
yield d
# end def tbl_iter
# end class Status
class Table_Iter (Page_Tree) :
def table_iter (self) :
root = self.tree.getroot ()
for div in root.findall (".//%s" % tag ("div")) :
if div.get ('id') == 'maincontent' :
break
tbl = div.find (".//%s" % tag ("table"))
if tbl is None :
return
for tr in tbl :
if tr [0].tag == tag ('th') :
continue
yield (self.tree.get_text (x) for x in tr)
# end def table_iter
# end class Table_Iter
class OLSR_Connections (Table_Iter) :
url = 'cgi-bin/luci/freifunk/olsr/'
retries = 2
timeout = 10
html_charset = 'utf-8' # force utf-8 encoding
def parse (self) :
self.neighbors = {}
for l in self.table_iter () :
neighbor, ip, lq, nlq, etx = l
lq, nlq, etx = (float (x) for x in (lq, nlq, etx))
self.neighbors [neighbor] = [ip, lq, nlq, etx]
# end def parse
# end class OLSR_Connections
class OLSR_Routes (Table_Iter) :
url = 'cgi-bin/luci/freifunk/olsr/routes'
retries = 2
timeout = 10
html_charset = 'utf-8' # force utf-8 encoding
def parse (self) :
self.iface_by_gw = {}
for l in self.table_iter () :
announced, gw, iface, metric, etx = l
if gw in self.iface_by_gw :
assert iface == self.iface_by_gw [gw]
else :
self.iface_by_gw [gw] = iface
# end def parse
# end class OLSR_Routes
class OpenWRT (autosuper) :
def __init__ (self, site, request) :
self.site = site
self.request = request
if 'interfaces' in self.request or 'ips' in self.request :
st = Status (site = site)
conn = OLSR_Connections (site = site)
route = OLSR_Routes (site = site)
self.version = st.version
assert len (st.wlans) <= 1
interfaces = {}
ips = {}
count = 0
for gw, ifname in pyk.iteritems (route.iface_by_gw) :
ip, lq, nlq, etx = conn.neighbors [gw]
i4 = Inet4 (ip, None, None, iface = ifname)
ips [i4] = 1
is_wlan = True
if lq == nlq == etx == 1.0 :
is_wlan = False
if ifname in interfaces :
iface = interfaces [ifname]
if not iface.is_wlan and is_wlan :
iface.is_wlan = True
iface.wlan_info = st.wlans [0]
else :
iface = Interface (count, ifname, None)
iface.is_wlan = is_wlan
if is_wlan :
iface.wlan_info = st.wlans [0]
count += 1
interfaces [ifname] = iface
if i4 not in iface.inet4 :
iface.append_inet4 (i4)
wl_if = None
for iface in pyk.itervalues (interfaces) :
if iface.is_wlan :
if wl_if :
m = "Duplicate wlan: %s/%s" % (iface.name, wl_if.name)
raise ValueError (m)
wl_if = iface
# check own ip
n = 'unknown'
i4 = Inet4 (self.request ['ip'], None, None, iface = n)
if i4 not in ips :
assert n not in interfaces
iface = interfaces [n] = Interface (count, n, None)
iface.append_inet4 (i4)
iface.is_wlan = False
if not wl_if and st.wlans :
iface.is_wlan = True
iface.wlan_info = st.wlans [0]
ips [i4] = True
self.request ['ips'] = ips
self.request ['interfaces'] = interfaces
self.request ['version'] = st.version
# end def __init__
# end class OpenWRT
|
In the context of an image deduplication system, this code is designed to remove or keep duplicate images. It does so by comparing their wavelet hashes which are calculated based on the content (similarity in features) of the image rather than their physical size or location. The comparison threshold `DIFF_THRES` and limit `LIMIT` determine when an image should be removed or not.
The function `calc_hash(img)` calculates a wavelet hash for each image. This is essentially a unique fingerprint of the image content that can help differentiate between similar images. The function `compare(hash1, hash2)` calculates the difference between two hashes indicating how dissimilar (in terms of number of 'differences') they are from one another.
The function `limit(img, std_hash, count)` determines whether an image should be removed or not based on its similarity to a standard image and the total count of similar images seen so far. It also updates the comparison standard (std_hash) when necessary.
The function `resize(img)` resizes an image if it's height exceeds 1000 pixels, preserving the aspect ratio while making sure the new dimensions are multiples of 1000.
Finally, the function `set_standard(images, filename)` sets a new standard for comparison and updates information about this new standard (filename, hash of image content, count of similar images). This is used when starting to process a new set of images or after an existing one has been fully processed.
Please note that all these functions are meant to be used in the main part of your program where they interact with user input and output as well as handle reading/writing from/to disk based on that interaction.
| # UCF Senior Design 2017-18
# Group 38
from PIL import Image
import cv2
import imagehash
import math
import numpy as np
DIFF_THRES = 20
LIMIT = 2
RESIZE = 1000
def calc_hash(img):
"""
Calculate the wavelet hash of the image
img: (ndarray) image file
"""
# resize image if height > 1000
img = resize(img)
return imagehash.whash(Image.fromarray(img))
def compare(hash1, hash2):
"""
Calculate the difference between two images
hash1: (array) first wavelet hash
hash2: (array) second wavelet hash
"""
return hash1 - hash2
def limit(img, std_hash, count):
"""
Determine whether image should be removed from image dictionary in main.py
img: (ndarray) image file
std_hash: (array) wavelet hash of comparison standard
count: (int) global count of images similar to comparison standard
"""
# calculate hash for given image
cmp_hash = calc_hash(img)
# compare to standard
diff = compare(std_hash, cmp_hash)
# image is similar to standard
if diff <= DIFF_THRES:
# if there are 3 similar images already, remove image
if count >= LIMIT:
return 'remove'
# non-similar image found
else:
# update comparison standard
return 'update_std'
# else continue reading images with same standard
return 'continue'
def resize(img):
"""
Resize an image
img: (ndarray) RGB color image
"""
# get dimensions of image
width = np.shape(img)[1]
height = np.shape(img)[0]
# if height of image is greater than 1000, resize it to 1000
if width > RESIZE:
# keep resize proportional
scale = RESIZE / width
resized_img = cv2.resize(
img, (RESIZE, math.floor(height / scale)), cv2.INTER_AREA)
# return resized image
return resized_img
# if height of image is less than 1000, return image unresized
return img
def set_standard(images, filename):
"""
Set new comparison standard and update information
images: (dictionary) dictionary containing all the image data
filename: (String) name of the image file
"""
return filename, calc_hash(images[filename]), 0
|
In the context of a Ruby program, this code is a command-line interface (CLI) application that runs the `main` function from the 'cli' module. This function serves as the entry point for executing various commands related to the Kubeflow Pipelines system.
The license at the top of the script specifies that it is subject to the Apache 2.0 License, meaning it can be used and modified under certain conditions. The specifics are found in the link provided: http://www.apache.org/licenses/LICENSE-2.0
A TODO comment suggests additional commands could be added or improvements made. Specifically, more functionality to compile Kubeflow Pipelines (a tool for creating and managing machine learning workflows), as well as tools for experiment management are suggested.
At the end of the script, it checks if the file is being run directly by checking `__name__ == '__main__'`. If true, it executes `main()`, which should be defined elsewhere in the codebase to handle command line arguments and invoke appropriate functions based on those arguments.
| # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .cli.cli import main
# TODO(hongyes): add more commands:
# kfp compile (migrate from dsl-compile)
# kfp experiment (manage experiments)
if __name__ == '__main__':
main()
|
In the context of a Python project that uses PyQt5, QtGui and QtCore for GUI creation and manipulation. It also involves handling time-related data in Unix timestamp format. The code is creating a class `Room_Item` which is a widget displaying details about a room: name, description, creation date, member count, etc. This class is inherited from two base classes - QWidget for GUI widgets and Ui_Form (a pre-generated UI file), and it has methods to set the text of different labels in this form based on some input data (room_data). The room_data is expected to be a dictionary with keys like 'naturalName', 'description', etc. For instance, self.data['naturalName'] provides the natural name of the room.
| import time
from PyQt5 import QtGui, QtCore
from ui.room_item import Ui_Form
from PyQt5.QtWidgets import QWidget
class Room_Item(QWidget,Ui_Form):
def __init__(self,parent=None,room_data=None):
super(Room_Item,self).__init__(parent)
self.setupUi(self)
self.data = room_data
self.setRoomInfo()
def setRoomInfo(self):
self.room_name.setText('{}({})'.format(self.data['naturalName'], self.data['roomName']))
self.description.setText("<a style='color:#BCBCBC'>{}</a>".format(self.data['description']))
timeStamp = int(self.data['creationDate']) / 1000
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d", timeArray)
self.create_time.setText("<a style='color:#BCBCBC'>{}</a>".format(otherStyleTime))
members = len(self.data['owners']) + len(self.data['admins']) + len(self.data['members'])
memberCounter = "<a style='color:#BCBCBC'>{}/{}</a>".format(members, ('∞' if self.data['maxUsers']==0 else self.data['maxUsers']))
self.member.setText(memberCounter) |
In the context of a graphical user interface application, we have an App class written in Python using the Toga library. The App is designed to run on Windows operating systems and manages the main window of the application.
The App class includes several methods that handle creation, menu creation, exception handling, and various actions related to the app's lifecycle such as setting up a context for the UI, handling exceptions in separate threads, running the app until exit, opening documents, showing about dialogs, etc.
Key attributes of the App class include:
- _is_exiting: A boolean attribute indicating whether the application is exiting or not.
- native: The WinForms Application object from Toga library for managing windows and UI elements.
- interface: An instance of the main app interface that this App represents.
The MainWindow class is a subclass of Window, which in turn has an implementation based on WinForms.MainWindow. It's designed to manage window closing procedures and includes a method called winforms_FormClosing which cancels window close event if application exit fails.
Besides these classes, there are other specific app types like DocumentApp that inherit from the App class with added functionalities for managing documents specifically. In this case, an additional 'Open...' command is created in their _create_app_commands method for opening files as a document. This code could be adapted for different contexts based on the requirements and platform it runs on.
| import asyncio
import re
import sys
import traceback
import toga
from toga import Key
from .keys import toga_to_winforms_key
from .libs import Threading, WinForms, shcore, user32, win_version
from .libs.proactor import WinformsProactorEventLoop
from .window import Window
class MainWindow(Window):
def winforms_FormClosing(self, sender, event):
if not self.interface.app._impl._is_exiting:
event.Cancel = not self.interface.app.exit()
class App:
_MAIN_WINDOW_CLASS = MainWindow
def __init__(self, interface):
self.interface = interface
self.interface._impl = self
# Winforms app exit is tightly bound to the close of the MainWindow.
# The FormClosing message on MainWindow calls app.exit(), which
# will then trigger the "on_exit" handler (which might abort the
# close). However, if app.exit() succeeds, it will request the
# Main Window to close... which calls app.exit().
# So - we have a flag that is only ever sent once a request has been
# made to exit the native app. This flag can be used to shortcut any
# window-level close handling.
self._is_exiting = False
self.loop = WinformsProactorEventLoop()
asyncio.set_event_loop(self.loop)
def create(self):
self.native = WinForms.Application
self.app_context = WinForms.ApplicationContext()
# Check the version of windows and make sure we are setting the DPI mode
# with the most up to date API
# Windows Versioning Check Sources : https://www.lifewire.com/windows-version-numbers-2625171
# and https://docs.microsoft.com/en-us/windows/release-information/
if win_version.Major >= 6: # Checks for Windows Vista or later
# Represents Windows 8.1 up to Windows 10 before Build 1703 which should use
# SetProcessDpiAwareness(True)
if ((win_version.Major == 6 and win_version.Minor == 3) or
(win_version.Major == 10 and win_version.Build < 15063)):
shcore.SetProcessDpiAwareness(True)
# Represents Windows 10 Build 1703 and beyond which should use
# SetProcessDpiAwarenessContext(-2)
elif win_version.Major == 10 and win_version.Build >= 15063:
user32.SetProcessDpiAwarenessContext(-2)
# Any other version of windows should use SetProcessDPIAware()
else:
user32.SetProcessDPIAware()
self.native.EnableVisualStyles()
self.native.SetCompatibleTextRenderingDefault(False)
self.interface.commands.add(
toga.Command(
lambda _: self.interface.about(),
'About {}'.format(self.interface.name),
group=toga.Group.HELP
),
toga.Command(None, 'Preferences', group=toga.Group.FILE),
# Quit should always be the last item, in a section on it's own
toga.Command(
lambda _: self.interface.exit(),
'Exit ' + self.interface.name,
shortcut=Key.MOD_1 + 'q',
group=toga.Group.FILE,
section=sys.maxsize
),
toga.Command(
lambda _: self.interface.visit_homepage(),
'Visit homepage',
enabled=self.interface.home_page is not None,
group=toga.Group.HELP
)
)
self._create_app_commands()
# Call user code to populate the main window
self.interface.startup()
self.create_menus()
self.interface.icon.bind(self.interface.factory)
self.interface.main_window._impl.set_app(self)
def create_menus(self):
self._menu_items = {}
self._menu_groups = {}
toga.Group.FILE.order = 0
menubar = WinForms.MenuStrip()
submenu = None
for cmd in self.interface.commands:
if cmd == toga.GROUP_BREAK:
submenu = None
elif cmd == toga.SECTION_BREAK:
submenu.DropDownItems.Add('-')
else:
submenu = self._submenu(cmd.group, menubar)
item = WinForms.ToolStripMenuItem(cmd.label)
if cmd.action:
item.Click += cmd._impl.as_handler()
item.Enabled = cmd.enabled
if cmd.shortcut is not None:
shortcut_keys = toga_to_winforms_key(cmd.shortcut)
item.ShortcutKeys = shortcut_keys
item.ShowShortcutKeys = True
cmd._impl.native.append(item)
self._menu_items[item] = cmd
submenu.DropDownItems.Add(item)
self.interface.main_window._impl.native.Controls.Add(menubar)
self.interface.main_window._impl.native.MainMenuStrip = menubar
self.interface.main_window.content.refresh()
def _submenu(self, group, menubar):
try:
return self._menu_groups[group]
except KeyError:
if group is None:
submenu = menubar
else:
parent_menu = self._submenu(group.parent, menubar)
submenu = WinForms.ToolStripMenuItem(group.label)
# Top level menus are added in a different way to submenus
if group.parent is None:
parent_menu.Items.Add(submenu)
else:
parent_menu.DropDownItems.Add(submenu)
self._menu_groups[group] = submenu
return submenu
def _create_app_commands(self):
# No extra menus
pass
def open_document(self, fileURL):
'''Add a new document to this app.'''
print("STUB: If you want to handle opening documents, implement App.open_document(fileURL)")
def winforms_thread_exception(self, sender, winforms_exc):
# The PythonException returned by Winforms doesn't give us
# easy access to the underlying Python stacktrace; so we
# reconstruct it from the string message.
# The Python message is helpfully included in square brackets,
# as the context for the first line in the .net stack trace.
# So, look for the closing bracket and the start of the Python.net
# stack trace. Then, reconstruct the line breaks internal to the
# remaining string.
print("Traceback (most recent call last):")
py_exc = winforms_exc.get_Exception()
full_stack_trace = py_exc.StackTrace
regex = re.compile(
r"^\[(?:'(.*?)', )*(?:'(.*?)')\] (?:.*?) Python\.Runtime",
re.DOTALL | re.UNICODE
)
stacktrace_relevant_lines = regex.findall(full_stack_trace)
if len(stacktrace_relevant_lines) == 0:
self.print_stack_trace(full_stack_trace)
else:
for lines in stacktrace_relevant_lines:
for line in lines:
self.print_stack_trace(line)
print(py_exc.Message)
@classmethod
def print_stack_trace(cls, stack_trace_line):
for level in stack_trace_line.split("', '"):
for line in level.split("\\n"):
if line:
print(line)
def run_app(self):
try:
self.create()
self.native.ThreadException += self.winforms_thread_exception
self.loop.run_forever(self.app_context)
except: # NOQA
traceback.print_exc()
def main_loop(self):
thread = Threading.Thread(Threading.ThreadStart(self.run_app))
thread.SetApartmentState(Threading.ApartmentState.STA)
thread.Start()
thread.Join()
def show_about_dialog(self):
message_parts = []
if self.interface.name is not None:
if self.interface.version is not None:
message_parts.append(
"{name} v{version}".format(
name=self.interface.name,
version=self.interface.version,
)
)
else:
message_parts.append(
"{name}".format(name=self.interface.name)
)
elif self.interface.version is not None:
message_parts.append(
"v{version}".format(version=self.interface.version)
)
if self.interface.author is not None:
message_parts.append(
"Author: {author}".format(author=self.interface.author)
)
if self.interface.description is not None:
message_parts.append(
"\n{description}".format(
description=self.interface.description
)
)
self.interface.main_window.info_dialog(
'About {}'.format(self.interface.name), "\n".join(message_parts)
)
def exit(self):
self._is_exiting = True
self.native.Exit()
def set_main_window(self, window):
self.app_context.MainForm = window._impl.native
def set_on_exit(self, value):
pass
def current_window(self):
self.interface.factory.not_implemented('App.current_window()')
def enter_full_screen(self, windows):
self.interface.factory.not_implemented('App.enter_full_screen()')
def exit_full_screen(self, windows):
self.interface.factory.not_implemented('App.exit_full_screen()')
def set_cursor(self, value):
self.interface.factory.not_implemented('App.set_cursor()')
def show_cursor(self):
self.interface.factory.not_implemented('App.show_cursor()')
def hide_cursor(self):
self.interface.factory.not_implemented('App.hide_cursor()')
def add_background_task(self, handler):
self.loop.call_soon(handler, self)
class DocumentApp(App):
def _create_app_commands(self):
self.interface.commands.add(
toga.Command(
lambda w: self.open_file,
label='Open...',
shortcut=Key.MOD_1 + 'o',
group=toga.Group.FILE,
section=0
),
)
def open_document(self, fileURL):
"""Open a new document in this app.
Args:
fileURL (str): The URL/path to the file to add as a document.
"""
self.interface.factory.not_implemented('DocumentApp.open_document()')
|