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
|
---|---|---|---|---|---|
1d691c24cb4e0fa9f4e9cf35bba7b9e700b6ad31 | 1,903 | # Plug in a druid, fetch the IIIF manifest, find the images, print the labels via Google Cloud Vision API
# https://cloud.google.com/vision/
# Setup:
# gem install faraday
# gem install iiif_google_cv
# gem install google-cloud # see https://github.com/googleapis/google-cloud-ruby
# You then need to have a valid .json service acccount key as described here:
# see https://cloud.google.com/vision/docs/quickstart?authuser=1
# and you need to set the "GOOGLE_APPLICATION_CREDENTIALS" environment file with the location of this json file
# NOTE: Only works with unrestricted public images on PURL pages
require 'json'
require 'faraday'
require 'google/cloud/vision'
require 'iiif_google_cv'
require 'pp'
project_id = "sul-ai-studio" # Your Google Cloud Platform project ID
puts "Enter druid (no prefix):"
druid = gets.chomp
iiif_manifest_url = "https://purl.stanford.edu/#{druid}/iiif/manifest"
puts iiif_manifest_url
puts
client = IiifGoogleCv::Client.new(manifest_url: iiif_manifest_url)
images = client.image_resources
begin
# Instantiates a client
vision = Google::Cloud::Vision.new project: project_id
images.each do |image|
# Performs label detection on the image file
results = vision.image(image)
puts "Labels for #{image}:"
results.labels.each do |label|
puts "#{label.description} : #{label.score.round(2)}"
end
puts
puts "Web entities for #{image}:"
results.web.entities.each do |entity|
puts "#{entity.description} : #{entity.score.round(2)}"
end
puts
end
rescue Google::Cloud::InvalidArgumentError => e
puts "ERROR"
puts "Google returned an error! (\"#{e.message}\". Its likely this image is restricted in some way (either not viewable at all or only as a thumbnail)"
rescue StandardError => e
puts "ERROR"
puts "Something bad happened and we don't know what. This might help: \"#{e.message}\"."
end
| 28.402985 | 155 | 0.726747 |
bfa9036881a02b7fe585e4ea254a631054b53bd8 | 3,488 | class MentorshipsController < EventBasedController
# GET /mentorships
# GET /mentorships.json
def index
@mentorships = policy_scope(@event.mentorships)
@mentorships = @mentorships.includes(:shift).includes(:mentee)
@mentorships = order_by_params @mentorships
respond_to do |format|
format.html # index.html.erb
format.json { render json: @mentorships }
end
end
# GET /mentorships/1
# GET /mentorships/1.json
def show
respond_to do |format|
format.html # show.html.erb
format.json { render json: @mentorship }
end
end
# GET /mentorships/1/changes
# GET /mentorships/1/changes.json
def changes
@audits = order_by_params @mentorship.audits, default_sort_column: 'version', default_sort_column_direction: 'desc'
respond_to do |format|
format.html # changes.html.haml
format.json { render json: @audits }
end
end
# GET /mentorships/new
# GET /mentorships/new.json
def new
@mentorship = @event.mentorships.build
@mentorship.outcome = Mentorship::OUTCOMES.first
params['mentee_id'].try do |mid|
@mentorship.mentee = Involvement.find mid
end
params['shift_id'].try do |sid|
@mentorship.shift = Shift.find sid
end
authorize @mentorship
respond_to do |format|
if @mentorship.valid?
format.html
format.json { render json: @mentorship }
else
format.html { render action: 'new', notice: "Must specify mentee and shift parameters" }
format.json { render json: @mentorship.errors, status: :unprocessable_entity }
end
end
end
# GET /mentorships/1/edit
def edit
end
# POST /mentorships
# POST /mentorships.json
def create
@mentorship = @event.mentorships.build mentorship_params
params['mentee_id'].presence.try {|mid| @mentorship.mentee = Involvement.find mid }
params['shift_id'].presence.try {|sid| @mentorship.shift = Shift.find sid}
authorize @mentorship
respond_to do |format|
if @mentorship.save
format.html { redirect_to [@mentorship.event, @mentorship], notice: 'Mentorship was successfully created.' }
format.json { render json: @mentorship, status: :created, location: @mentorship }
else
format.html { render action: "new" }
format.json { render json: @mentorship.errors, status: :unprocessable_entity }
end
end
end
# PUT /mentorships/1
# PUT /mentorships/1.json
def update
respond_to do |format|
if @mentorship.update_attributes(mentorship_params)
format.html { redirect_to [@mentorship.event, @mentorship], notice: 'Mentorship was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @mentorship.errors, status: :unprocessable_entity }
end
end
end
# DELETE /mentorships/1
# DELETE /mentorships/1.json
def destroy
@mentorship.destroy
respond_to do |format|
format.html { redirect_to event_mentorships_url(@mentorship.event_id) }
format.json { head :no_content }
end
end
def subject_record
@mentorship
end
def load_subject_record_by_id
@mentorship = @event.mentorships.find(params[:id])
end
def default_sort_column
'shifts.start_time'
end
private
def mentorship_params
params.require(:mentorship).
permit(*policy(@mentorship || Mentorship.new).permitted_attributes)
end
end
| 28.590164 | 119 | 0.680333 |
113de555f977cab34d1b747ec94e0810ec21401b | 184 | require 'sinatra'
require "sinatra/json"
require "sinatra/activerecord"
require_relative 'models/world'
get '/' do
end
get '/worlds/' do
json(World.all.select(:id, :name))
end
| 13.142857 | 36 | 0.711957 |
628204a82bbd6aa7c87adaf4693dd384e929c8fa | 2,272 | cask "docker" do
if MacOS.version <= :el_capitan
version "18.06.1-ce-mac73,26764"
sha256 "3429eac38cf0d198039ad6e1adce0016f642cdb914a34c67ce40f069cdb047a5"
else
version "3.0.4,51218"
sha256 "5c389dd9842e2f5027b8c073e80495f43c01b72e2ac48e98151d1429675e7f93"
end
url "https://desktop.docker.com/mac/stable/#{version.after_comma}/Docker.dmg"
name "Docker Desktop"
name "Docker Community Edition"
name "Docker CE"
desc "App to build and share containerized applications and microservices"
homepage "https://www.docker.com/products/docker-desktop"
livecheck do
url "https://desktop.docker.com/mac/stable/appcast.xml"
strategy :sparkle
end
auto_updates true
app "Docker.app"
uninstall delete: [
"/Library/PrivilegedHelperTools/com.docker.vmnetd",
"/private/var/tmp/com.docker.vmnetd.socket",
"/usr/local/bin/docker",
"/usr/local/bin/docker-compose",
"/usr/local/bin/docker-credential-desktop",
"/usr/local/bin/docker-credential-ecr-login",
"/usr/local/bin/docker-credential-osxkeychain",
"/usr/local/bin/hyperkit",
"/usr/local/bin/kubectl",
"/usr/local/bin/kubectl.docker",
"/usr/local/bin/notary",
"/usr/local/bin/vpnkit",
],
launchctl: [
"com.docker.helper",
"com.docker.vmnetd",
],
quit: "com.docker.docker"
zap trash: [
"/usr/local/bin/docker-compose.backup",
"/usr/local/bin/docker.backup",
"~/Library/Application Support/Docker Desktop",
"~/Library/Application Scripts/com.docker.helper",
"~/Library/Caches/KSCrashReports/Docker",
"~/Library/Caches/com.docker.docker",
"~/Library/Caches/com.plausiblelabs.crashreporter.data/com.docker.docker",
"~/Library/Containers/com.docker.docker",
"~/Library/Containers/com.docker.helper",
"~/Library/Group Containers/group.com.docker",
"~/Library/Preferences/com.docker.docker.plist",
"~/Library/Preferences/com.electron.docker-frontend.plist",
"~/Library/Saved Application State/com.electron.docker-frontend.savedState",
"~/Library/Logs/Docker Desktop",
],
rmdir: [
"~/Library/Caches/KSCrashReports",
"~/Library/Caches/com.plausiblelabs.crashreporter.data",
]
end
| 33.910448 | 80 | 0.683979 |
ed15810906f1ca5fe5b4711dfc9df818d883ea92 | 4,280 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you 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.
# frozen_string_literal: true
require 'elastic_apm/span/context'
module ElasticAPM
# @api private
class Span
extend Forwardable
include ChildDurations::Methods
# @api private
class Outcome
FAILURE = "failure"
SUCCESS = "success"
UNKNOWN = "unknown"
def self.from_http_status(code)
code.to_i >= 400 ? FAILURE : SUCCESS
end
end
DEFAULT_TYPE = 'custom'
# rubocop:disable Metrics/ParameterLists
def initialize(
name:,
transaction:,
trace_context:,
parent:,
type: nil,
subtype: nil,
action: nil,
context: nil,
stacktrace_builder: nil,
sync: nil,
exit_span: false
)
@name = name
if subtype.nil? && type&.include?('.')
@type, @subtype, @action = type.split('.')
else
@type = type || DEFAULT_TYPE
@subtype = subtype
@action = action
end
@transaction = transaction
@parent = parent
@trace_context = trace_context || parent.trace_context.child
@sample_rate = transaction.sample_rate
@context = context || Span::Context.new(sync: sync)
@stacktrace_builder = stacktrace_builder
@exit_span = exit_span
end
# rubocop:enable Metrics/ParameterLists
def_delegators :@trace_context, :trace_id, :parent_id, :id
attr_accessor(
:action,
:exit_span,
:name,
:original_backtrace,
:outcome,
:subtype,
:trace_context,
:type
)
attr_reader(
:context,
:duration,
:parent,
:sample_rate,
:self_time,
:stacktrace,
:timestamp,
:transaction
)
alias :exit_span? :exit_span
# life cycle
def start(clock_start = Util.monotonic_micros)
@timestamp = Util.micros
@clock_start = clock_start
@parent.child_started
self
end
def stop(clock_end = Util.monotonic_micros)
@duration ||= (clock_end - @clock_start)
@parent.child_stopped
@self_time = @duration - child_durations.duration
self
end
def done(clock_end: Util.monotonic_micros)
stop clock_end
self
end
def prepare_for_serialization!
build_stacktrace! if should_build_stacktrace?
self.original_backtrace = nil # release original
end
def stopped?
!!duration
end
def started?
!!timestamp
end
def running?
started? && !stopped?
end
def set_destination(address: nil, port: nil, service: nil, cloud: nil)
context.destination = Span::Context::Destination.new(
address: address,
port: port,
service: service,
cloud: cloud
)
end
def inspect
"<ElasticAPM::Span id:#{trace_context&.id}" \
" name:#{name.inspect}" \
" type:#{type.inspect}" \
" subtype:#{subtype.inspect}" \
" action:#{action.inspect}" \
" exit_span:#{exit_span.inspect}" \
'>'
end
private
def build_stacktrace!
@stacktrace = @stacktrace_builder.build(original_backtrace, type: :span)
end
def should_build_stacktrace?
@stacktrace_builder && original_backtrace && long_enough_for_stacktrace?
end
def long_enough_for_stacktrace?
min_duration =
@stacktrace_builder.config.span_frames_min_duration_us
return true if min_duration < 0
return false if min_duration == 0
duration >= min_duration
end
end
end
| 23.646409 | 78 | 0.639953 |
6271584d02c1f143776a27dd90f445d2c37478e9 | 156 | # Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
SocialAuth::Application.initialize!
| 26 | 52 | 0.794872 |
8750368047e747c352fbd27c2767f2c03a45e227 | 99 | class FanaticPluser
extend Rusby::Core
rusby!
def plusplus(number)
number + 1
end
end
| 11 | 22 | 0.686869 |
d5f55621cceb9e0cf467b052f1ec9c728f527cb8 | 36,571 | require 'test_helper'
describe BrNfe::Product::Operation::NfeConsultaProtocolo do
subject { FactoryGirl.build(:product_operation_nfe_consulta_protocolo) }
describe '#aliases' do
it { must_have_alias_attribute :chNFe, :chave_nfe }
end
describe 'Validations' do
it { must validate_presence_of(:chave_nfe) }
it { must validate_length_of(:chave_nfe).is_equal_to(44) }
end
describe '#xml_builder' do
it "Deve renderizar o XML e setar o valor na variavel @xml_builder" do
subject.expects(:render_xml).returns('<xml>OK</xml>')
subject.xml_builder.must_equal '<xml>OK</xml>'
subject.instance_variable_get(:@xml_builder).must_equal '<xml>OK</xml>'
end
it "Se já houver valor setado na variavel @xml_builder não deve renderizar o xml novamente" do
subject.instance_variable_set(:@xml_builder, '<xml>OK</xml>')
subject.expects(:render_xml).never
subject.xml_builder.must_equal '<xml>OK</xml>'
end
end
context "Validações para NF-e versão 2.01" do
before do
subject.assign_attributes(nfe_version: :v2_01, ibge_code_of_issuer_uf: '42', env: :test)
end
describe "Validação do XML através do XSD" do
context "for XML Version 2.01" do
before { subject.stubs(:gateway_xml_version).returns(:v2_01) }
it "Deve ser válido em ambiente de produção" do
subject.env = :production
nfe_must_be_valid_by_schema 'consSitNFe_v2.01.xsd'
end
it "Deve ser válido em ambiente de homologação" do
subject.env = :test
nfe_must_be_valid_by_schema 'consSitNFe_v2.01.xsd'
end
end
end
end
context "Validações para NF-e versão 3.10" do
before do
subject.assign_attributes(nfe_version: :v3_10, ibge_code_of_issuer_uf: '42', env: :test)
end
describe "Validação do XML através do XSD" do
context "for XML Version 3.10" do
before { subject.stubs(:gateway_xml_version).returns(:v3_10) }
it "Deve ser válido em ambiente de produção" do
subject.env = :production
nfe_must_be_valid_by_schema 'consSitNFe_v3.10.xsd'
end
it "Deve ser válido em ambiente de homologação" do
subject.env = :test
nfe_must_be_valid_by_schema 'consSitNFe_v3.10.xsd'
end
end
end
describe 'REQUEST MUST BE SET RESPONSE CORRECTLY' do
let(:response_fail) { read_fixture('product/response/v3.10/nfe_consulta_protocolo/fail.xml') }
let(:response_success_without_event){ read_fixture('product/response/v3.10/nfe_consulta_protocolo/success_without.xml') }
let(:response_success_one_event) { read_fixture('product/response/v3.10/nfe_consulta_protocolo/success_one.xml') }
let(:response_success_many_events_without_cancel) { read_fixture('product/response/v3.10/nfe_consulta_protocolo/success_many_without_cancel.xml') }
let(:response_success_many_events_with_cancel) { read_fixture('product/response/v3.10/nfe_consulta_protocolo/success_many_with_cancel.xml') }
let(:xml_nfe_without_proc) { read_fixture('product/response/v3.10/nfe_consulta_protocolo/nfe_original/without_proc.xml') }
let(:xml_nfe_with_proc) { read_fixture('product/response/v3.10/nfe_consulta_protocolo/nfe_original/with_proc.xml') }
before do
savon.mock!
stub_request(:get, subject.client_wsdl.globals[:wsdl]).to_return(status: 200, body: read_fixture('product/wsdl/NfeConsulta2.xml') )
end
after { savon.unmock! }
it "Quando a resposta reotrnar com algum erro não deve instanciar os eventos" do
subject.original_xml = xml_nfe_with_proc
savon.expects(subject.method_wsdl).returns( response_fail )
subject.request
response = subject.response
response.must_be_kind_of BrNfe::Product::Response::NfeConsultaProtocolo
response.environment.must_equal :test
response.app_version.must_equal 'SVRS201610061504'
response.processed_at.must_equal Time.parse('2017-01-04T15:45:02-02:00')
response.protocol.must_be_nil
response.request_status.must_equal :success
response.processing_status_code.must_equal '226'
response.processing_status_motive.must_equal 'Rejeicao: Codigo da UF do Emitente diverge da UF autorizadora'
response.processing_status.must_equal :error
response.nota_fiscal.must_be_nil
response.main_event.must_be_nil
response.events.must_be_empty
end
it "Quando retornar apenas o protocolo da NF-e e não tiver nenhum evento deve apenas setar o protocolo no XML da NF-e" do
subject.original_xml = xml_nfe_without_proc
savon.expects(subject.method_wsdl).returns( response_success_without_event )
subject.request
response = subject.response
response.must_be_kind_of BrNfe::Product::Response::NfeConsultaProtocolo
response.environment.must_equal :test
response.app_version.must_equal 'SVRS201610061504'
response.processed_at.must_equal Time.parse('2017-01-03T08:56:39-02:00')
response.protocol.must_be_nil
response.request_status.must_equal :success
response.processing_status_code.must_equal '100'
response.processing_status_motive.must_equal 'Autorizado o uso da NF-e'
response.processing_status.must_equal :success
response.main_event.must_be_nil
response.events.must_be_empty
nf = response.nota_fiscal
nf.wont_be_nil
nf.processed_at.must_equal Time.parse('2017-01-03T08:53:13-02:00')
nf.protocol.must_equal '342170000000903'
nf.digest_value.must_equal '2N5tbfnT9V4oRxiesTyBLP9tAVE='
nf.status_code.must_equal '100'
nf.status_motive.must_equal 'Autorizado o uso da NF-e'
nf.chave_de_acesso.must_equal '42170108897094000155550010000000051201601010'
nf.situation.must_equal :authorized
nf.xml.must_equal xml_nfe_with_proc, "Deveria adicionar o protocolo da NF-e e a NF dentro da tag nfeProc"
end
it "Quando retornar apenas 1 evento deve seta-lo como o evento principal e também adicionar na lista de eventos" do
subject.original_xml = xml_nfe_with_proc
savon.expects(subject.method_wsdl).returns( response_success_one_event )
subject.request
response = subject.response
response.environment.must_equal :test
response.app_version.must_equal 'SVRS201610061504'
response.processed_at.must_equal Time.parse('2017-01-03T08:56:39-02:00')
response.protocol.must_be_nil
response.request_status.must_equal :success
response.processing_status_code.must_equal '135'
response.processing_status_motive.must_equal 'Evento registrado e vinculado a NF-e'
response.processing_status.must_equal :success
response.main_event.wont_be_nil
response.events.size.must_equal 1
response.main_event.must_equal response.events[0]
event = response.main_event
event.codigo_orgao.must_equal '35'
event.status_code.must_equal '135'
event.status_motive.must_equal 'Evento registrado e vinculado a NF-e'
event.code.must_equal '110110'
event.sequence.must_equal 1
event.cpf_cnpj_destino.must_equal '04962355000112'
event.sent_at.must_equal Time.parse('2014-02-05T16:06:30-02:00')
event.registred_at.must_equal Time.parse('2014-02-05T16:06:32-02:00')
event.event_protocol.must_equal ''
event.authorization_protocol.must_equal '135140000457555'
event.xml.must_equal read_fixture('product/response/v3.10/nfe_consulta_protocolo/event_xml/one_event.xml')
nf = response.nota_fiscal
nf.processed_at.must_equal Time.parse('2017-01-03T08:53:13-02:00')
nf.protocol.must_equal '342170000000903'
nf.digest_value.must_equal '2N5tbfnT9V4oRxiesTyBLP9tAVE='
nf.status_code.must_equal '100'
nf.status_motive.must_equal 'Autorizado o uso da NF-e'
nf.chave_de_acesso.must_equal '42170108897094000155550010000000051201601010'
nf.situation.must_equal :adjusted
nf.xml.must_equal xml_nfe_with_proc, "Não deve duplicar os protocolos se já houver algum protocolo em nfeProc"
end
it "Quando tem mais de um evento e não tiver Cancelamneto deve setar todos os eventos na lista e setar o de maior sequencia no evento principal" do
subject.original_xml = xml_nfe_with_proc
savon.expects(subject.method_wsdl).returns( response_success_many_events_without_cancel )
subject.request
response = subject.response
response.environment.must_equal :production
response.app_version.must_equal 'SVRS201610061505'
response.processed_at.must_equal Time.parse('2017-01-03T08:56:39-02:00')
response.protocol.must_be_nil
response.request_status.must_equal :success
response.processing_status_code.must_equal '101'
response.processing_status_motive.must_equal 'Cancelamento de NF-e homologado'
response.processing_status.must_equal :success
response.main_event.wont_be_nil
response.events.size.must_equal 3
events = response.events.sort_by{|e| [e.sequence.to_i, (e.registred_at||Time.current)] }
response.main_event.must_equal events[2]
events[0].codigo_orgao.must_equal '35'
events[0].status_code.must_equal '135'
events[0].status_motive.must_equal 'Evento registrado e vinculado a NF-e'
events[0].code.must_equal '110110'
events[0].sequence.must_equal 1
events[0].cpf_cnpj_destino.must_equal '04962355000112'
events[0].sent_at.must_equal Time.parse('2014-02-05T16:06:30-02:00')
events[0].registred_at.must_equal Time.parse('2014-02-05T16:06:32-02:00')
events[0].event_protocol.must_equal ''
events[0].authorization_protocol.must_equal '135140000457555'
events[0].description.must_equal 'Carta de Correcao'
events[0].justification.must_equal ''
events[0].correction_text.must_equal 'teste de consulta de nfe corrigida primeira coorecao para consulta de nota'
events[0].xml.must_equal read_fixture('product/response/v3.10/nfe_consulta_protocolo/event_xml/event_1.xml')
events[1].codigo_orgao.must_equal '35'
events[1].status_code.must_equal '135'
events[1].status_motive.must_equal 'Evento registrado e vinculado a NF-e'
events[1].code.must_equal '110110'
events[1].sequence.must_equal 2
events[1].cpf_cnpj_destino.must_equal '04962355000112'
events[1].sent_at.must_equal Time.parse('2014-02-05T16:06:30-02:00')
events[1].registred_at.must_equal Time.parse('2014-02-05T16:06:32-02:00')
events[1].event_protocol.must_equal ''
events[1].authorization_protocol.must_equal '135140000457416'
events[1].description.must_equal 'Carta de Correcao'
events[1].justification.must_equal ''
events[1].correction_text.must_equal 'teste de consulta de nfe corrigida segunda coorecao para consulta de nota'
events[1].xml.must_equal read_fixture('product/response/v3.10/nfe_consulta_protocolo/event_xml/event_2.xml')
events[2].codigo_orgao.must_equal '35'
events[2].status_code.must_equal '135'
events[2].status_motive.must_equal 'Evento registrado e vinculado a NF-e'
events[2].code.must_equal '110110'
events[2].sequence.must_equal 3
events[2].cpf_cnpj_destino.must_equal '04962355000112'
events[2].sent_at.must_equal Time.parse('2014-02-05T16:06:30-02:00')
events[2].registred_at.must_equal Time.parse('2014-02-05T16:06:32-02:00')
events[2].event_protocol.must_equal ''
events[2].authorization_protocol.must_equal '135140000457417'
events[2].description.must_equal 'Carta de Correcao'
events[2].justification.must_equal ''
events[2].correction_text.must_equal 'teste de consulta de nfe corrigida terceiro coorecao para consulta de nota'
events[2].xml.must_equal read_fixture('product/response/v3.10/nfe_consulta_protocolo/event_xml/event_3.xml')
nf = response.nota_fiscal
nf.processed_at.must_equal Time.parse('2017-01-03T08:53:13-02:00')
nf.protocol.must_equal '342170000000903'
nf.digest_value.must_equal '2N5tbfnT9V4oRxiesTyBLP9tAVE='
nf.status_code.must_equal '100'
nf.status_motive.must_equal 'Autorizado o uso da NF-e'
nf.chave_de_acesso.must_equal '42170108897094000155550010000000051201601010'
nf.situation.must_equal :adjusted
nf.xml.must_equal xml_nfe_with_proc, "Não deve duplicar os protocolos se já houver algum protocolo em nfeProc"
end
it "Quando tem mais de um evento e tem um evento de Cancelamento, sempre deve ser o principal" do
subject.original_xml = xml_nfe_with_proc
savon.expects(subject.method_wsdl).returns( response_success_many_events_with_cancel )
subject.request
response = subject.response
response.environment.must_equal :production
response.app_version.must_equal 'SVRS201610061505'
response.processed_at.must_equal Time.parse('2017-01-03T08:56:39-02:00')
response.protocol.must_be_nil
response.request_status.must_equal :success
response.processing_status_code.must_equal '101'
response.processing_status_motive.must_equal 'Cancelamento de NF-e homologado'
response.processing_status.must_equal :success
response.main_event.wont_be_nil
response.events.size.must_equal 3
events = response.events.sort_by{|e| [e.sequence.to_i, (e.registred_at||Time.current)] }
response.main_event.must_equal events[1]
events[0].codigo_orgao.must_equal '35'
events[0].status_code.must_equal '135'
events[0].status_motive.must_equal 'Evento registrado e vinculado a NF-e'
events[0].code.must_equal '110110'
events[0].sequence.must_equal 1
events[0].cpf_cnpj_destino.must_equal '04962355000112'
events[0].sent_at.must_equal Time.parse('2014-02-05T16:06:30-02:00')
events[0].registred_at.must_equal Time.parse('2014-02-05T16:06:32-02:00')
events[0].event_protocol.must_equal ''
events[0].authorization_protocol.must_equal '135140000457555'
events[0].description.must_equal 'Carta de Correcao'
events[0].justification.must_equal ''
events[0].correction_text.must_equal 'teste de consulta de nfe corrigida primeira coorecao para consulta de nota'
events[0].xml.must_equal read_fixture('product/response/v3.10/nfe_consulta_protocolo/event_xml/event_1.xml')
events[2].codigo_orgao.must_equal '35'
events[2].status_code.must_equal '135'
events[2].status_motive.must_equal 'Evento registrado e vinculado a NF-e'
events[2].code.must_equal '110110'
events[2].sequence.must_equal 2
events[2].cpf_cnpj_destino.must_equal '04962355000112'
events[2].sent_at.must_equal Time.parse('2014-02-05T16:06:30-02:00')
events[2].registred_at.must_equal Time.parse('2014-02-05T16:06:32-02:00')
events[2].event_protocol.must_equal ''
events[2].authorization_protocol.must_equal '135140000457416'
events[2].description.must_equal 'Carta de Correcao'
events[2].justification.must_equal ''
events[2].correction_text.must_equal 'teste de consulta de nfe corrigida segunda coorecao para consulta de nota'
events[2].xml.must_equal read_fixture('product/response/v3.10/nfe_consulta_protocolo/event_xml/event_2.xml')
events[1] = response.main_event
events[1].codigo_orgao.must_equal '42'
events[1].status_code.must_equal '135'
events[1].status_motive.must_equal 'Evento registrado e vinculado a NF-e'
events[1].code.must_equal '110111'
events[1].sequence.must_equal 1
events[1].cpf_cnpj_destino.must_equal '00090742403050'
events[1].sent_at.must_equal Time.parse('2017-01-03T08:54:58-02:00')
events[1].registred_at.must_equal Time.parse('2017-01-03T08:55:05-02:00')
events[1].event_protocol.must_equal '342170000000903'
events[1].authorization_protocol.must_equal '342170000000906'
events[1].description.must_equal 'Cancelamento'
events[1].justification.must_equal 'Cancelamento para teste'
events[1].correction_text.must_equal ''
events[1].xml.must_equal read_fixture('product/response/v3.10/nfe_consulta_protocolo/event_xml/event_cancel.xml')
nf = response.nota_fiscal
nf.processed_at.must_equal Time.parse('2017-01-03T08:53:13-02:00')
nf.protocol.must_equal '342170000000903'
nf.digest_value.must_equal '2N5tbfnT9V4oRxiesTyBLP9tAVE='
nf.status_code.must_equal '100'
nf.status_motive.must_equal 'Autorizado o uso da NF-e'
nf.chave_de_acesso.must_equal '42170108897094000155550010000000051201601010'
nf.situation.must_equal :canceled
nf.xml.must_equal xml_nfe_with_proc, "Não deve duplicar os protocolos se já houver algum protocolo em nfeProc"
end
end
describe 'Configurações por UF dos parametros para instanciar o client Soap' do
let(:client_wsdl) { subject.client_wsdl }
describe 'UF 12 - Acre' do
before { subject.ibge_code_of_issuer_uf = '12' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 27 - Alagoas' do
before { subject.ibge_code_of_issuer_uf = '27' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 16 - Amapá' do
before { subject.ibge_code_of_issuer_uf = '16' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 13 - Amazonas' do
before { subject.ibge_code_of_issuer_uf = '13' }
it "configurações para e emissão normal no ambiente de produção" do
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.sefaz.am.gov.br/services2/services/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "configurações para e emissão normal no ambiente de teste" do
subject.env = :test
client_wsdl.globals[:wsdl].must_equal 'https://homnfe.sefaz.am.gov.br/services2/services/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCRS_for_SVC_mode
end
end
describe 'UF 29 - Bahia' do
before { subject.ibge_code_of_issuer_uf = '29' }
it "configurações para e emissão normal no ambiente de produção" do
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.sefaz.ba.gov.br/webservices/NfeConsulta/NfeConsulta.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "configurações para e emissão normal no ambiente de teste" do
subject.env = :test
client_wsdl.globals[:wsdl].must_equal 'https://hnfe.sefaz.ba.gov.br/webservices/NfeConsulta/NfeConsulta.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCRS_for_SVC_mode
end
end
describe 'UF 23 - Ceará' do
before { subject.ibge_code_of_issuer_uf = '23' }
it "configurações para e emissão normal no ambiente de produção" do
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.sefaz.ce.gov.br/nfe2/services/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "configurações para e emissão normal no ambiente de teste" do
subject.env = :test
client_wsdl.globals[:wsdl].must_equal 'https://nfeh.sefaz.ce.gov.br/nfe2/services/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCRS_for_SVC_mode
end
end
describe 'UF 53 - Distrito Federal' do
before { subject.ibge_code_of_issuer_uf = '53' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 32 - Espírito Santo' do
before { subject.ibge_code_of_issuer_uf = '32' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 52 - Goiás' do
before { subject.ibge_code_of_issuer_uf = '52' }
it "configurações para e emissão normal no ambiente de produção" do
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.sefaz.go.gov.br/nfe/services/v2/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal true
client_wsdl.globals[:headers].must_equal( {:'Content-Type' => 'application/soap+xml; charset=utf-8'} )
end
it "configurações para e emissão normal no ambiente de teste" do
subject.env = :test
client_wsdl.globals[:wsdl].must_equal 'https://homolog.sefaz.go.gov.br/nfe/services/v2/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal true
client_wsdl.globals[:headers].must_equal( {:'Content-Type' => 'application/soap+xml; charset=utf-8'} )
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCRS_for_SVC_mode
end
end
describe 'UF 21 - Maranhão' do
before { subject.ibge_code_of_issuer_uf = '21' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVAN
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCRS_for_SVC_mode
end
end
describe 'UF 51 - Mato Grosso' do
before { subject.ibge_code_of_issuer_uf = '51' }
it "configurações para e emissão normal no ambiente de produção" do
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.sefaz.mt.gov.br/nfews/v2/services/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "configurações para e emissão normal no ambiente de teste" do
subject.env = :test
client_wsdl.globals[:wsdl].must_equal 'https://homologacao.sefaz.mt.gov.br/nfews/v2/services/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCRS_for_SVC_mode
end
end
describe 'UF 50 - Mato Grosso do Sul' do
before { subject.ibge_code_of_issuer_uf = '50' }
it "configurações para e emissão normal no ambiente de produção" do
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.fazenda.ms.gov.br/producao/services2/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "configurações para e emissão normal no ambiente de teste" do
subject.env = :test
client_wsdl.globals[:wsdl].must_equal 'https://homologacao.nfe.ms.gov.br/homologacao/services2/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCRS_for_SVC_mode
end
end
describe 'UF 31 - Minas Gerais' do
before { subject.ibge_code_of_issuer_uf = '31' }
it "configurações para e emissão normal no ambiente de produção" do
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.fazenda.mg.gov.br/nfe2/services/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "configurações para e emissão normal no ambiente de teste" do
subject.env = :test
client_wsdl.globals[:wsdl].must_equal 'https://hnfe.fazenda.mg.gov.br/nfe2/services/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 15 - Pará' do
before { subject.ibge_code_of_issuer_uf = '15' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVAN
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCRS_for_SVC_mode
end
end
describe 'UF 25 - Paraíba' do
before { subject.ibge_code_of_issuer_uf = '25' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 41 - Paraná' do
before { subject.ibge_code_of_issuer_uf = '41' }
it "configurações para e emissão normal no ambiente de produção" do
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.fazenda.pr.gov.br/nfe/NFeConsulta3?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "configurações para e emissão normal no ambiente de teste" do
subject.env = :test
client_wsdl.globals[:wsdl].must_equal 'https://homologacao.nfe.fazenda.pr.gov.br/nfe/NFeConsulta3?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCRS_for_SVC_mode
end
end
describe 'UF 26 - Pernambuco' do
before { subject.ibge_code_of_issuer_uf = '26' }
it "configurações para e emissão normal no ambiente de produção" do
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.sefaz.pe.gov.br/nfe-service/services/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "configurações para e emissão normal no ambiente de teste" do
subject.env = :test
client_wsdl.globals[:wsdl].must_equal 'https://nfehomolog.sefaz.pe.gov.br/nfe-service/services/NfeConsulta2?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCRS_for_SVC_mode
end
end
describe 'UF 22 - Piauí' do
before { subject.ibge_code_of_issuer_uf = '22' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCRS_for_SVC_mode
end
end
describe 'UF 33 - Rio de Janeiro' do
before { subject.ibge_code_of_issuer_uf = '33' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 24 - Rio Grande do Norte' do
before { subject.ibge_code_of_issuer_uf = '24' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 43 - Rio Grande do Sul' do
before { subject.ibge_code_of_issuer_uf = '43' }
it "configurações para e emissão normal no ambiente de produção" do
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.sefazrs.rs.gov.br/ws/NfeConsulta/NfeConsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "configurações para e emissão normal no ambiente de teste" do
subject.env = :test
client_wsdl.globals[:wsdl].must_equal 'https://nfe-homologacao.sefazrs.rs.gov.br/ws/NfeConsulta/NfeConsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 11 - Rondônia' do
before { subject.ibge_code_of_issuer_uf = '11' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 14 - Roraima' do
before { subject.ibge_code_of_issuer_uf = '14' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 42 - Santa Catarina' do
before { subject.ibge_code_of_issuer_uf = '42' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 35 - São Paulo' do
before { subject.ibge_code_of_issuer_uf = '35' }
it "configurações para e emissão normal no ambiente de produção" do
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.fazenda.sp.gov.br/ws/nfeconsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "configurações para e emissão normal no ambiente de teste" do
subject.env = :test
client_wsdl.globals[:wsdl].must_equal 'https://homologacao.nfe.fazenda.sp.gov.br/ws/nfeconsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 28 - Sergipe' do
before { subject.ibge_code_of_issuer_uf = '28' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
describe 'UF 17 - Tocantins' do
before { subject.ibge_code_of_issuer_uf = '17' }
it "Deve utilizar o servidor SVRS para emissão normal" do
must_use_SVRS
end
it "Deve usar o servidor SVCAN para emissão em Contingência" do
must_use_SVCAN_for_SVC_mode
end
end
end
end
private
def must_use_SVRS
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://nfe.svrs.rs.gov.br/ws/NfeConsulta/NfeConsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
subject.instance_variable_set(:@client_wsdl, nil)
subject.env = :test
client_wsdl = subject.client_wsdl
client_wsdl.globals[:wsdl].must_equal 'https://nfe-homologacao.svrs.rs.gov.br/ws/NfeConsulta/NfeConsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
def must_use_SVAN
subject.env = :production
client_wsdl.globals[:wsdl].must_equal 'https://www.sefazvirtual.fazenda.gov.br/NfeConsulta2/NfeConsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
subject.instance_variable_set(:@client_wsdl, nil)
subject.env = :test
client_wsdl = subject.client_wsdl
client_wsdl.globals[:wsdl].must_equal 'https://hom.sefazvirtual.fazenda.gov.br/NfeConsulta2/NfeConsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
def must_use_SVCAN_for_SVC_mode
subject.assign_attributes(env: :production, tipo_emissao: :svc)
client_wsdl.globals[:wsdl].must_equal 'https://www.svc.fazenda.gov.br/NfeConsulta2/NfeConsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
subject.instance_variable_set(:@client_wsdl, nil)
subject.assign_attributes(env: :test, tipo_emissao: :svc)
client_wsdl = subject.client_wsdl
client_wsdl.globals[:wsdl].must_equal 'https://hom.svc.fazenda.gov.br/NfeConsulta2/NfeConsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :TLSv1
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
def must_use_SVCRS_for_SVC_mode
subject.assign_attributes(env: :production, tipo_emissao: :svc)
client_wsdl.globals[:wsdl].must_equal 'https://nfe.svrs.rs.gov.br/ws/NfeConsulta/NfeConsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
subject.instance_variable_set(:@client_wsdl, nil)
subject.assign_attributes(env: :test, tipo_emissao: :svc)
client_wsdl = subject.client_wsdl
client_wsdl.globals[:wsdl].must_equal 'https://nfe-homologacao.svrs.rs.gov.br/ws/NfeConsulta/NfeConsulta2.asmx?wsdl'
client_wsdl.globals[:ssl_verify_mode].must_equal :none
client_wsdl.globals[:ssl_version].must_equal :SSLv3
client_wsdl.globals[:follow_redirects].must_equal false
client_wsdl.globals[:headers].must_be_nil
end
end | 46.351077 | 151 | 0.755954 |
62453be1ed9cce94973f1115c01e942058ffe58e | 3,331 | # Puppet provider for mysql
class Puppet::Provider::Mysql < Puppet::Provider
# Without initvars commands won't work.
initvars
# Make sure we find mysql commands on CentOS and FreeBSD
ENV['PATH'] = ENV['PATH'] + ':/usr/libexec:/usr/local/libexec:/usr/local/bin'
# rubocop:disable Style/HashSyntax
commands :mysql => 'mysql'
commands :mysqld => 'mysqld'
commands :mysqladmin => 'mysqladmin'
# rubocop:enable Style/HashSyntax
# Optional defaults file
def self.defaults_file
"--defaults-extra-file=#{Facter.value(:root_home)}/.my.cnf" if File.file?("#{Facter.value(:root_home)}/.my.cnf")
end
def self.mysqld_type
# find the mysql "dialect" like mariadb / mysql etc.
mysqld_version_string.scan(%r{mariadb}i) { return 'mariadb' }
mysqld_version_string.scan(%r{\s\(percona}i) { return 'percona' }
'mysql'
end
def mysqld_type
self.class.mysqld_type
end
def self.mysqld_version_string
# As the possibility of the mysqld being remote we need to allow the version string to be overridden,
# this can be done by facter.value as seen below. In the case that it has not been set and the facter
# value is nil we use the mysql -v command to ensure we report the correct version of mysql for later use cases.
@mysqld_version_string ||= Facter.value(:mysqld_version) || mysqld('-V')
end
def mysqld_version_string
self.class.mysqld_version_string
end
def self.mysqld_version
# note: be prepared for '5.7.6-rc-log' etc results
# versioncmp detects 5.7.6-log to be newer then 5.7.6
# this is why we need the trimming.
mysqld_version_string.scan(%r{\d+\.\d+\.\d+}).first unless mysqld_version_string.nil?
end
def mysqld_version
self.class.mysqld_version
end
def defaults_file
self.class.defaults_file
end
def self.users
mysql([defaults_file, '-NBe', "SELECT CONCAT(User, '@',Host) AS User FROM mysql.user"].compact).split("\n")
end
# Optional parameter to run a statement on the MySQL system database.
def self.system_database
'--database=mysql'
end
def system_database
self.class.system_database
end
# Take root@localhost and munge it to 'root'@'localhost'
def self.cmd_user(user)
"'#{user.sub('@', "'@'")}'"
end
# Take root.* and return ON `root`.*
def self.cmd_table(table)
table_string = ''
# We can't escape *.* so special case this.
table_string << if table == '*.*'
'*.*'
# Special case also for PROCEDURES
elsif table.start_with?('PROCEDURE ')
table.sub(%r{^PROCEDURE (.*)(\..*)}, 'PROCEDURE `\1`\2')
else
table.sub(%r{^(.*)(\..*)}, '`\1`\2')
end
table_string
end
def self.cmd_privs(privileges)
return 'ALL PRIVILEGES' if privileges.include?('ALL')
priv_string = ''
privileges.each do |priv|
priv_string << "#{priv}, "
end
# Remove trailing , from the last element.
priv_string.sub(%r{, $}, '')
end
# Take in potential options and build up a query string with them.
def self.cmd_options(options)
option_string = ''
options.each do |opt|
option_string << ' WITH GRANT OPTION' if opt == 'GRANT'
end
option_string
end
end
| 30.281818 | 116 | 0.643651 |
3985e1e33de083d665681bceae4fbe09f755dfa2 | 140 | require "new_gem/version"
module NewGem
class Error < StandardError; end
def self.testName
"this is a succesful test"
end
end
| 14 | 34 | 0.714286 |
9164f2ef905ae9500e9e186a0b9c4f30909bb1e6 | 78 | json.array! @players do |player|
json.partial!('player', player: player)
end | 26 | 41 | 0.717949 |
215786f30ea6cd99e4837a3dbd2ff27f9924dbb9 | 637 | describe "Helpers" do
describe 'Helpers#current_user' do
it "returns the current user" do
@user1 = User.create(:username => "skittles123", :password => "iluvskittles", :balance => 1000)
session = {
:user_id => 1
}
expect(Helpers.current_user(session)).to be_an_instance_of(User)
end
end
describe 'Helpers#is_logged_in?' do
it "returns true or false" do
@user1 = User.create(:username => "skittles123", :password => "iluvskittles", :balance => 1000)
session = {
:user_id => 1
}
expect(Helpers.is_logged_in?(session)).to eq(true)
end
end
end
| 23.592593 | 101 | 0.615385 |
7a78f04bff0669d6886c3774f307b95874a16510 | 1,071 | # Copyright (C) 2011 Rocky Bernstein <[email protected]>
require 'rubygems'; require 'require_relative'
require_relative '../command'
require_relative '../load_cmds'
class Trepan::Command::CompleteCommand < Trepan::Command
unless defined?(HELP)
NAME = File.basename(__FILE__, '.rb')
HELP = <<-HELP
#{NAME} COMMAND-PREFIX
List the completions for the rest of the line as a command.
HELP
CATEGORY = 'support'
NEED_STACK = false
SHORT_HELP = 'List the completions for the rest of the line as a command'
end
# This method runs the command
def run(args) # :nodoc
last_arg = @proc.cmd_argstr.end_with?(' ') ? '' : args[-1]
@proc.complete(@proc.cmd_argstr, last_arg).each do |match|
msg match
end
end
end
if __FILE__ == $0
# Demo it.
require_relative '../mock'
dbgr, cmd = MockDebugger::setup
%w(d b bt).each do |prefix|
cmd.proc.instance_variable_set('@cmd_argstr', prefix)
cmd.run [cmd.name, prefix]
puts '=' * 40
end
cmd.run %w(#{cmd.name} fdafsasfda)
puts '=' * 40
end
| 26.775 | 80 | 0.659197 |
915a455f8ef025843c7a4144c24900d4716eb51d | 1,166 | #
# Copyright 2014 Chef Software, 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.
#
name "perl_pg_driver"
default_version "3.3.0"
dependency "perl"
dependency "cpanminus"
dependency "postgresql"
license "Artistic"
license_file "README"
license_file "LICENSES/artistic.txt"
version "3.5.3" do
source md5: "21cdf31a8d1f77466920375aa766c164"
end
version "3.3.0" do
source md5: "547de1382a47d66872912fe64282ff55"
end
source url: "http://search.cpan.org/CPAN/authors/id/T/TU/TURNSTEP/DBD-Pg-#{version}.tar.gz"
relative_path "DBD-Pg-#{version}"
build do
env = with_standard_compiler_flags(with_embedded_path)
command "cpanm -v --notest .", env: env
end
| 26.5 | 91 | 0.759005 |
f70fd22e66e1133103a0f2d28cea1a779c4cf5e5 | 14,160 | =begin
#Custom Workflow Actions
#Create custom workflow actions
The version of the OpenAPI document: v4
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.3.1
=end
require 'date'
module Hubspot
module Automation
module Actions
class FieldTypeDefinition
# The input field name.
attr_accessor :name
# The data type of the field.
attr_accessor :type
# Controls how the field appears in HubSpot.
attr_accessor :field_type
# A list of valid options for the field value.
attr_accessor :options
# A URL that will accept HTTPS requests when the valid options for the field are fetched.
attr_accessor :options_url
# This can be set to `OWNER` if the field should contain a HubSpot owner value.
attr_accessor :referenced_object_type
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'name' => :'name',
:'type' => :'type',
:'field_type' => :'fieldType',
:'options' => :'options',
:'options_url' => :'optionsUrl',
:'referenced_object_type' => :'referencedObjectType'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'name' => :'String',
:'type' => :'String',
:'field_type' => :'String',
:'options' => :'Array<Option>',
:'options_url' => :'String',
:'referenced_object_type' => :'String'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `Hubspot::Automation::Actions::FieldTypeDefinition` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `Hubspot::Automation::Actions::FieldTypeDefinition`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'name')
self.name = attributes[:'name']
end
if attributes.key?(:'type')
self.type = attributes[:'type']
end
if attributes.key?(:'field_type')
self.field_type = attributes[:'field_type']
end
if attributes.key?(:'options')
if (value = attributes[:'options']).is_a?(Array)
self.options = value
end
end
if attributes.key?(:'options_url')
self.options_url = attributes[:'options_url']
end
if attributes.key?(:'referenced_object_type')
self.referenced_object_type = attributes[:'referenced_object_type']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if @name.nil?
invalid_properties.push('invalid value for "name", name cannot be nil.')
end
if @type.nil?
invalid_properties.push('invalid value for "type", type cannot be nil.')
end
if @options.nil?
invalid_properties.push('invalid value for "options", options cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @name.nil?
return false if @type.nil?
type_validator = EnumAttributeValidator.new('String', ["string", "number", "bool", "datetime", "enumeration", "date", "phone_number", "currency_number", "json", "object_coordinates"])
return false unless type_validator.valid?(@type)
field_type_validator = EnumAttributeValidator.new('String', ["booleancheckbox", "checkbox", "date", "file", "number", "phonenumber", "radio", "select", "text", "textarea", "calculation_equation", "calculation_rollup", "calculation_score", "calculation_read_time", "unknown"])
return false unless field_type_validator.valid?(@field_type)
return false if @options.nil?
referenced_object_type_validator = EnumAttributeValidator.new('String', ["CONTACT", "COMPANY", "DEAL", "ENGAGEMENT", "TICKET", "OWNER", "PRODUCT", "LINE_ITEM", "BET_DELIVERABLE_SERVICE", "CONTENT", "CONVERSATION", "BET_ALERT", "PORTAL", "QUOTE", "FORM_SUBMISSION_INBOUNDDB", "QUOTA", "UNSUBSCRIBE", "COMMUNICATION", "FEEDBACK_SUBMISSION", "ATTRIBUTION", "SALESFORCE_SYNC_ERROR", "RESTORABLE_CRM_OBJECT", "HUB", "LANDING_PAGE", "PRODUCT_OR_FOLDER", "TASK", "FORM", "MARKETING_EMAIL", "AD_ACCOUNT", "AD_CAMPAIGN", "AD_GROUP", "AD", "KEYWORD", "CAMPAIGN", "SOCIAL_CHANNEL", "SOCIAL_POST", "SITE_PAGE", "BLOG_POST", "IMPORT", "EXPORT", "CTA", "TASK_TEMPLATE", "AUTOMATION_PLATFORM_FLOW", "OBJECT_LIST", "NOTE", "MEETING_EVENT", "CALL", "EMAIL", "PUBLISHING_TASK", "CONVERSATION_SESSION", "CONTACT_CREATE_ATTRIBUTION", "INVOICE", "MARKETING_EVENT", "CONVERSATION_INBOX", "CHATFLOW", "MEDIA_BRIDGE", "SEQUENCE", "SEQUENCE_STEP", "FORECAST", "SNIPPET", "TEMPLATE", "UNKNOWN"])
return false unless referenced_object_type_validator.valid?(@referenced_object_type)
true
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] type Object to be assigned
def type=(type)
validator = EnumAttributeValidator.new('String', ["string", "number", "bool", "datetime", "enumeration", "date", "phone_number", "currency_number", "json", "object_coordinates"])
unless validator.valid?(type)
fail ArgumentError, "invalid value for \"type\", must be one of #{validator.allowable_values}."
end
@type = type
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] field_type Object to be assigned
def field_type=(field_type)
validator = EnumAttributeValidator.new('String', ["booleancheckbox", "checkbox", "date", "file", "number", "phonenumber", "radio", "select", "text", "textarea", "calculation_equation", "calculation_rollup", "calculation_score", "calculation_read_time", "unknown"])
unless validator.valid?(field_type)
fail ArgumentError, "invalid value for \"field_type\", must be one of #{validator.allowable_values}."
end
@field_type = field_type
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] referenced_object_type Object to be assigned
def referenced_object_type=(referenced_object_type)
validator = EnumAttributeValidator.new('String', ["CONTACT", "COMPANY", "DEAL", "ENGAGEMENT", "TICKET", "OWNER", "PRODUCT", "LINE_ITEM", "BET_DELIVERABLE_SERVICE", "CONTENT", "CONVERSATION", "BET_ALERT", "PORTAL", "QUOTE", "FORM_SUBMISSION_INBOUNDDB", "QUOTA", "UNSUBSCRIBE", "COMMUNICATION", "FEEDBACK_SUBMISSION", "ATTRIBUTION", "SALESFORCE_SYNC_ERROR", "RESTORABLE_CRM_OBJECT", "HUB", "LANDING_PAGE", "PRODUCT_OR_FOLDER", "TASK", "FORM", "MARKETING_EMAIL", "AD_ACCOUNT", "AD_CAMPAIGN", "AD_GROUP", "AD", "KEYWORD", "CAMPAIGN", "SOCIAL_CHANNEL", "SOCIAL_POST", "SITE_PAGE", "BLOG_POST", "IMPORT", "EXPORT", "CTA", "TASK_TEMPLATE", "AUTOMATION_PLATFORM_FLOW", "OBJECT_LIST", "NOTE", "MEETING_EVENT", "CALL", "EMAIL", "PUBLISHING_TASK", "CONVERSATION_SESSION", "CONTACT_CREATE_ATTRIBUTION", "INVOICE", "MARKETING_EVENT", "CONVERSATION_INBOX", "CHATFLOW", "MEDIA_BRIDGE", "SEQUENCE", "SEQUENCE_STEP", "FORECAST", "SNIPPET", "TEMPLATE", "UNKNOWN"])
unless validator.valid?(referenced_object_type)
fail ArgumentError, "invalid value for \"referenced_object_type\", must be one of #{validator.allowable_values}."
end
@referenced_object_type = referenced_object_type
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
name == o.name &&
type == o.type &&
field_type == o.field_type &&
options == o.options &&
options_url == o.options_url &&
referenced_object_type == o.referenced_object_type
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[name, type, field_type, options, options_url, referenced_object_type].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
Hubspot::Automation::Actions.const_get(type).build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
end
end
| 42.017804 | 979 | 0.598658 |
ffe0130f576a42a74ce963c0cd1edfcb6016337f | 1,028 | test_name 'FM-3804 - C94728 - Plug-in Sync Module from Master with Prerequisites Satisfied on Agent'
step 'install IBM_Installation_Manager dependencies:'
['puppet-archive', 'puppetlabs-stdlib', 'puppetlabs-concat'].each do |dep|
on(master, puppet("module install #{dep}"))
end
step 'Install dsestero/download_uncompress module on the agent'
confine_block(:except, roles: ['master', 'dashboard', 'database']) do
agents.each do |agent|
on(agent, '/opt/puppetlabs/puppet/bin/puppet module install dsestero-download_uncompress')
end
end
step 'Install ibm_installation_manager Module'
proj_root = File.expand_path(File.join(File.dirname(__FILE__), '../../../'))
staging = { module_name: 'puppetlabs-ibm_installation_manager' }
local = { module_name: 'ibm_installation_manager', source: proj_root,
target_module_path: '/etc/puppetlabs/code/environments/production/modules' }
# in CI install from staging forge, otherwise from local
install_dev_puppet_module_on(master, options[:forge_host] ? staging : local)
| 44.695652 | 100 | 0.764591 |
18083a58587ffe5b25ca3e1d4bdbd84cec689ba2 | 10,633 | # encoding: utf-8
require "test_helper"
class TestRooOpenOffice < Minitest::Test
def test_openoffice_download_uri_and_zipped
port = 12_345
file = "rata.ods.zip"
start_local_server(file, port) do
url = "#{local_server(port)}/#{file}"
workbook = roo_class.new(url, packed: :zip)
assert_in_delta 0.001, 505.14, workbook.cell("c", 33).to_f
end
end
def test_download_uri_with_invalid_host
assert_raises(RuntimeError) do
roo_class.new("http://examples.com/file.ods")
end
end
def test_download_uri_with_query_string
file = filename("simple_spreadsheet")
port = 12_346
url = "#{local_server(port)}/#{file}?query-param=value"
start_local_server(file, port) do
spreadsheet = roo_class.new(url)
assert_equal "Task 1", spreadsheet.cell("f", 4)
end
end
def test_openoffice_zipped
workbook = roo_class.new(File.join(TESTDIR, "bode-v1.ods.zip"), packed: :zip)
assert workbook
assert_equal 'ist "e" im Nenner von H(s)', workbook.cell("b", 5)
end
def test_should_raise_file_not_found_error
assert_raises(IOError) do
roo_class.new(File.join("testnichtvorhanden", "Bibelbund.ods"))
end
end
def test_file_warning_default_is_error
expected_message = "test/files/numbers1.xls is not an openoffice spreadsheet"
assert_raises(TypeError, expected_message) do
roo_class.new(File.join(TESTDIR, "numbers1.xls"))
end
assert_raises(TypeError) do
roo_class.new(File.join(TESTDIR, "numbers1.xlsx"))
end
end
def test_file_warning_error
options = { packed: false, file_warning: :error }
assert_raises(TypeError) do
roo_class.new(File.join(TESTDIR, "numbers1.xls"), options)
end
assert_raises(TypeError) do
roo_class.new(File.join(TESTDIR, "numbers1.xlsx"), options)
end
end
def test_file_warning_warning
assert_raises(ArgumentError) do
options = { packed: false, file_warning: :warning }
roo_class.new(File.join(TESTDIR, "numbers1.xlsx"), options)
end
end
def test_file_warning_ignore
options = { packed: false, file_warning: :ignore }
assert roo_class.new(File.join(TESTDIR, "type_openoffice.xlsx"), options), "Should not throw an error"
end
def test_encrypted_file
workbook = roo_class.new(File.join(TESTDIR, "encrypted-letmein.ods"), password: "letmein")
assert_equal "Hello World", workbook.cell("a", 1)
end
def test_encrypted_file_requires_password
assert_raises(ArgumentError) do
roo_class.new(File.join(TESTDIR, "encrypted-letmein.ods"))
end
end
def test_encrypted_file_with_incorrect_password
assert_raises(ArgumentError) do
roo_class.new(File.join(TESTDIR, "encrypted-letmein.ods"), password: "badpassword")
end
end
# 2011-08-11
def test_bug_openoffice_formula_missing_letters
# NOTE: This document was created using LibreOffice. The formulas seem
# different from a document created using OpenOffice.
#
# TODO: translate
# Bei den OpenOffice-Dateien ist in diesem Feld in der XML-
# Datei of: als Prefix enthalten, waehrend in dieser Datei
# irgendetwas mit oooc: als Prefix verwendet wird.
workbook = roo_class.new(File.join(TESTDIR, "dreimalvier.ods"))
assert_equal "=SUM([.A1:.D1])", workbook.formula("e", 1)
assert_equal "=SUM([.A2:.D2])", workbook.formula("e", 2)
assert_equal "=SUM([.A3:.D3])", workbook.formula("e", 3)
expected_formulas = [
[1, 5, "=SUM([.A1:.D1])"],
[2, 5, "=SUM([.A2:.D2])"],
[3, 5, "=SUM([.A3:.D3])"],
]
assert_equal expected_formulas, workbook.formulas
end
def test_header_with_brackets_open_office
options = { name: "advanced_header", format: :openoffice }
with_each_spreadsheet(options) do |workbook|
parsed_head = workbook.parse(headers: true)
assert_equal "Date(yyyy-mm-dd)", workbook.cell("A", 1)
assert_equal parsed_head[0].keys, ["Date(yyyy-mm-dd)"]
assert_equal parsed_head[0].values, ["Date(yyyy-mm-dd)"]
end
end
def test_office_version
with_each_spreadsheet(name: "numbers1", format: :openoffice) do |workbook|
assert_equal "1.0", workbook.officeversion
end
end
def test_bug_contiguous_cells
with_each_spreadsheet(name: "numbers1", format: :openoffice) do |workbook|
workbook.default_sheet = "Sheet4"
assert_equal Date.new(2007, 06, 16), workbook.cell("a", 1)
assert_equal 10, workbook.cell("b", 1)
assert_equal 10, workbook.cell("c", 1)
assert_equal 10, workbook.cell("d", 1)
assert_equal 10, workbook.cell("e", 1)
end
end
def test_italo_table
with_each_spreadsheet(name: "simple_spreadsheet_from_italo", format: :openoffice) do |workbook|
assert_equal "1", workbook.cell("A", 1)
assert_equal "1", workbook.cell("B", 1)
assert_equal "1", workbook.cell("C", 1)
assert_equal 1, workbook.cell("A", 2).to_i
assert_equal 2, workbook.cell("B", 2).to_i
assert_equal 1, workbook.cell("C", 2).to_i
assert_equal 1, workbook.cell("A", 3)
assert_equal 3, workbook.cell("B", 3)
assert_equal 1, workbook.cell("C", 3)
assert_equal "A", workbook.cell("A", 4)
assert_equal "A", workbook.cell("B", 4)
assert_equal "A", workbook.cell("C", 4)
assert_equal 0.01, workbook.cell("A", 5)
assert_equal 0.01, workbook.cell("B", 5)
assert_equal 0.01, workbook.cell("C", 5)
assert_equal 0.03, workbook.cell("a", 5) + workbook.cell("b", 5) + workbook.cell("c", 5)
# Cells values in row 1:
assert_equal "1:string", [workbook.cell(1, 1), workbook.celltype(1, 1)].join(":")
assert_equal "1:string", [workbook.cell(1, 2), workbook.celltype(1, 2)].join(":")
assert_equal "1:string", [workbook.cell(1, 3), workbook.celltype(1, 3)].join(":")
# Cells values in row 2:
assert_equal "1:string", [workbook.cell(2, 1), workbook.celltype(2, 1)].join(":")
assert_equal "2:string", [workbook.cell(2, 2), workbook.celltype(2, 2)].join(":")
assert_equal "1:string", [workbook.cell(2, 3), workbook.celltype(2, 3)].join(":")
# Cells values in row 3:
assert_equal "1:float", [workbook.cell(3, 1), workbook.celltype(3, 1)].join(":")
assert_equal "3:float", [workbook.cell(3, 2), workbook.celltype(3, 2)].join(":")
assert_equal "1:float", [workbook.cell(3, 3), workbook.celltype(3, 3)].join(":")
# Cells values in row 4:
assert_equal "A:string", [workbook.cell(4, 1), workbook.celltype(4, 1)].join(":")
assert_equal "A:string", [workbook.cell(4, 2), workbook.celltype(4, 2)].join(":")
assert_equal "A:string", [workbook.cell(4, 3), workbook.celltype(4, 3)].join(":")
# Cells values in row 5:
assert_equal "0.01:percentage", [workbook.cell(5, 1), workbook.celltype(5, 1)].join(":")
assert_equal "0.01:percentage", [workbook.cell(5, 2), workbook.celltype(5, 2)].join(":")
assert_equal "0.01:percentage", [workbook.cell(5, 3), workbook.celltype(5, 3)].join(":")
end
end
def test_formula_openoffice
with_each_spreadsheet(name: "formula", format: :openoffice) do |workbook|
assert_equal 1, workbook.cell("A", 1)
assert_equal 2, workbook.cell("A", 2)
assert_equal 3, workbook.cell("A", 3)
assert_equal 4, workbook.cell("A", 4)
assert_equal 5, workbook.cell("A", 5)
assert_equal 6, workbook.cell("A", 6)
assert_equal 21, workbook.cell("A", 7)
assert_equal :formula, workbook.celltype("A", 7)
assert_equal "=[Sheet2.A1]", workbook.formula("C", 7)
assert_nil workbook.formula("A", 6)
expected_formulas = [
[7, 1, "=SUM([.A1:.A6])"],
[7, 2, "=SUM([.$A$1:.B6])"],
[7, 3, "=[Sheet2.A1]"],
[8, 2, "=SUM([.$A$1:.B7])"],
]
assert_equal expected_formulas, workbook.formulas(workbook.sheets.first)
# setting a cell
workbook.set("A", 15, 41)
assert_equal 41, workbook.cell("A", 15)
workbook.set("A", 16, "41")
assert_equal "41", workbook.cell("A", 16)
workbook.set("A", 17, 42.5)
assert_equal 42.5, workbook.cell("A", 17)
end
end
def test_bug_ric
with_each_spreadsheet(name: "ric", format: :openoffice) do |workbook|
assert workbook.empty?("A", 1)
assert workbook.empty?("B", 1)
assert workbook.empty?("C", 1)
assert workbook.empty?("D", 1)
expected = 1
letter = "e"
while letter <= "u"
assert_equal expected, workbook.cell(letter, 1)
letter.succ!
expected += 1
end
assert_equal "J", workbook.cell("v", 1)
assert_equal "P", workbook.cell("w", 1)
assert_equal "B", workbook.cell("x", 1)
assert_equal "All", workbook.cell("y", 1)
assert_equal 0, workbook.cell("a", 2)
assert workbook.empty?("b", 2)
assert workbook.empty?("c", 2)
assert workbook.empty?("d", 2)
assert_equal "B", workbook.cell("e", 2)
assert_equal "B", workbook.cell("f", 2)
assert_equal "B", workbook.cell("g", 2)
assert_equal "B", workbook.cell("h", 2)
assert_equal "B", workbook.cell("i", 2)
assert_equal "B", workbook.cell("j", 2)
assert_equal "B", workbook.cell("k", 2)
assert_equal "B", workbook.cell("l", 2)
assert_equal "B", workbook.cell("m", 2)
assert_equal "B", workbook.cell("n", 2)
assert_equal "B", workbook.cell("o", 2)
assert_equal "B", workbook.cell("p", 2)
assert_equal "B", workbook.cell("q", 2)
assert_equal "B", workbook.cell("r", 2)
assert_equal "B", workbook.cell("s", 2)
assert workbook.empty?("t", 2)
assert workbook.empty?("u", 2)
assert_equal 0, workbook.cell("v", 2)
assert_equal 0, workbook.cell("w", 2)
assert_equal 15, workbook.cell("x", 2)
assert_equal 15, workbook.cell("y", 2)
end
end
def test_mehrteilig
with_each_spreadsheet(name: "Bibelbund1", format: :openoffice) do |workbook|
assert_equal "Tagebuch des Sekret\303\244rs. Letzte Tagung 15./16.11.75 Schweiz", workbook.cell(45, "A")
end
end
def test_cell_openoffice_html_escape
with_each_spreadsheet(name: "html-escape", format: :openoffice) do |workbook|
assert_equal "'", workbook.cell(1, 1)
assert_equal "&", workbook.cell(2, 1)
assert_equal ">", workbook.cell(3, 1)
assert_equal "<", workbook.cell(4, 1)
assert_equal "`", workbook.cell(5, 1)
# test_openoffice_zipped will catch issues with "
end
end
def roo_class
Roo::OpenOffice
end
def filename(name)
"#{name}.ods"
end
end
| 36.665517 | 113 | 0.645914 |
1d93308080b9e151f62f456f82e61f914b5ba2ea | 124 | module Rcommerce
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
end
| 20.666667 | 54 | 0.806452 |
26bf4800dc487dba5ffe58a4e190deff8a095770 | 3,005 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2015 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-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
require 'rack/test'
describe 'API::V3::WorkPackages::AvailableProjectsOnEditAPI', type: :request do
include API::V3::Utilities::PathHelper
let(:edit_role) do
FactoryGirl.create(:role, permissions: [:edit_work_packages,
:view_work_packages])
end
let(:move_role) do
FactoryGirl.create(:role, permissions: [:move_work_packages])
end
let(:project) { FactoryGirl.create(:project) }
let(:target_project) { FactoryGirl.create(:project) }
let(:work_package) { FactoryGirl.create(:work_package, project: project) }
let(:user) do
user = FactoryGirl.create(:user,
member_in_project: project,
member_through_role: edit_role)
FactoryGirl.create(:member,
user: user,
project: target_project,
roles: [move_role])
user
end
before do
allow(User).to receive(:current).and_return(user)
get api_v3_paths.available_projects_on_edit(work_package.id)
end
context 'w/ the necessary permissions' do
it_behaves_like 'API V3 collection response', 1, 1, 'Project'
it 'has the project for which the move_work_packages permission exists' do
expect(response.body).to be_json_eql(target_project.id).at_path('_embedded/elements/0/id')
end
end
context 'w/o the edit_work_packages permission' do
let(:edit_role) do
FactoryGirl.create(:role, permissions: [:view_work_packages])
end
it { expect(response.status).to eq(403) }
end
context 'w/o the view_work_packages permission' do
let(:edit_role) do
FactoryGirl.create(:role, permissions: [:edit_work_packages])
end
it { expect(response.status).to eq(404) }
end
end
| 34.54023 | 96 | 0.699168 |
aca3e3dfcf872abf051a49f12d070df0f06962cd | 6,710 | #-- copyright
# OpenProject Costs Plugin
#
# Copyright (C) 2009 - 2014 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.
#
# 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.
#++
require File.dirname(__FILE__) + '/../spec_helper'
describe User, '#destroy', type: :model do
let(:user) { FactoryBot.create(:user) }
let(:user2) { FactoryBot.create(:user) }
let(:substitute_user) { DeletedUser.first }
let(:project) { FactoryBot.create(:valid_project) }
before do
user
user2
end
after do
User.current = nil
end
shared_examples_for 'costs updated journalized associated object' do
before do
User.current = user2
associations.each do |association|
associated_instance.send(association.to_s + '=', user2)
end
associated_instance.save!
User.current = user # in order to have the content journal created by the user
associated_instance.reload
associations.each do |association|
associated_instance.send(association.to_s + '=', user)
end
associated_instance.save!
user.destroy
associated_instance.reload
end
it { expect(associated_class.find_by_id(associated_instance.id)).to eq(associated_instance) }
it 'should replace the user on all associations' do
associations.each do |association|
expect(associated_instance.send(association)).to eq(substitute_user)
end
end
it { expect(associated_instance.journals.first.user).to eq(user2) }
it 'should update first journal changed_data' do
associations.each do |association|
expect(associated_instance.journals.first.changed_data["#{association}_id".to_sym].last).to eq(user2.id)
end
end
it { expect(associated_instance.journals.last.user).to eq(substitute_user) }
it 'should update second journal changed_data' do
associations.each do |association|
expect(associated_instance.journals.last.changed_data["#{association}_id".to_sym].last).to eq(substitute_user.id)
end
end
end
shared_examples_for 'costs created journalized associated object' do
before do
User.current = user # in order to have the content journal created by the user
associations.each do |association|
associated_instance.send(association.to_s + '=', user)
end
associated_instance.save!
User.current = user2
associated_instance.reload
associations.each do |association|
associated_instance.send(association.to_s + '=', user2)
end
associated_instance.save!
user.destroy
associated_instance.reload
end
it { expect(associated_class.find_by_id(associated_instance.id)).to eq(associated_instance) }
it 'should keep the current user on all associations' do
associations.each do |association|
expect(associated_instance.send(association)).to eq(user2)
end
end
it { expect(associated_instance.journals.first.user).to eq(substitute_user) }
it 'should update the first journal' do
associations.each do |association|
expect(associated_instance.journals.first.changed_data["#{association}_id".to_sym].last).to eq(substitute_user.id)
end
end
it { expect(associated_instance.journals.last.user).to eq(user2) }
it 'should update the last journal' do
associations.each do |association|
expect(associated_instance.journals.last.changed_data["#{association}_id".to_sym].first).to eq(substitute_user.id)
expect(associated_instance.journals.last.changed_data["#{association}_id".to_sym].last).to eq(user2.id)
end
end
end
describe 'WHEN the user updated a cost object' do
let(:associations) { [:author] }
let(:associated_instance) { FactoryBot.build(:variable_cost_object) }
let(:associated_class) { CostObject }
it_should_behave_like 'costs updated journalized associated object'
end
describe 'WHEN the user created a cost object' do
let(:associations) { [:author] }
let(:associated_instance) { FactoryBot.build(:variable_cost_object) }
let(:associated_class) { CostObject }
it_should_behave_like 'costs created journalized associated object'
end
describe 'WHEN the user has a labor_budget_item associated' do
let(:item) { FactoryBot.build(:labor_budget_item, user: user) }
before do
item.save!
user.destroy
end
it { expect(LaborBudgetItem.find_by_id(item.id)).to eq(item) }
it { expect(item.user_id).to eq(user.id) }
end
describe 'WHEN the user has a cost entry' do
let(:work_package) { FactoryBot.create(:work_package) }
let(:entry) {
FactoryBot.build(:cost_entry, user: user,
project: work_package.project,
units: 100.0,
spent_on: Date.today,
work_package: work_package,
comments: '')
}
before do
FactoryBot.create(:member, project: work_package.project,
user: user,
roles: [FactoryBot.build(:role)])
entry.save!
user.destroy
entry.reload
end
it { expect(entry.user_id).to eq(user.id) }
end
describe 'WHEN the user is assigned an hourly rate' do
let(:hourly_rate) {
FactoryBot.build(:hourly_rate, user: user,
project: project)
}
before do
hourly_rate.save!
user.destroy
end
it { expect(HourlyRate.find_by_id(hourly_rate.id)).to eq(hourly_rate) }
it { expect(hourly_rate.reload.user_id).to eq(user.id) }
end
describe 'WHEN the user is assigned a default hourly rate' do
let(:default_hourly_rate) {
FactoryBot.build(:default_hourly_rate, user: user,
project: project)
}
before do
default_hourly_rate.save!
user.destroy
end
it { expect(DefaultHourlyRate.find_by_id(default_hourly_rate.id)).to eq(default_hourly_rate) }
it { expect(default_hourly_rate.reload.user_id).to eq(user.id) }
end
end
| 33.55 | 122 | 0.671386 |
28946520b63ff789ba37284493b94394c3e066cb | 67 | module Wordpress
class APICallException < StandardError; end
end
| 16.75 | 45 | 0.820896 |
e81e119ab6e16fc00cbe46d82bd2f55091f7bca8 | 348 | class CreateGeolocations < ActiveRecord::Migration
def self.up
create_table :geolocations do |t|
t.integer :zip
t.string :state_code
t.string :state
t.string :city
t.float :longitude
t.float :latitude
t.timestamps
end
end
def self.down
drop_table :geolocations
end
end
| 15.818182 | 50 | 0.62069 |
b96c18f46a483444e14188419b680f258923d7a5 | 7,270 | # Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
require 'date'
require_relative 'attach_volume_details'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# AttachParavirtualizedVolumeDetails model.
class Core::Models::AttachParavirtualizedVolumeDetails < Core::Models::AttachVolumeDetails
# Whether to enable in-transit encryption for the data volume's paravirtualized attachment. The default value is false.
# @return [BOOLEAN]
attr_accessor :is_pv_encryption_in_transit_enabled
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'device': :'device',
'display_name': :'displayName',
'instance_id': :'instanceId',
'is_read_only': :'isReadOnly',
'type': :'type',
'volume_id': :'volumeId',
'is_pv_encryption_in_transit_enabled': :'isPvEncryptionInTransitEnabled'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'device': :'String',
'display_name': :'String',
'instance_id': :'String',
'is_read_only': :'BOOLEAN',
'type': :'String',
'volume_id': :'String',
'is_pv_encryption_in_transit_enabled': :'BOOLEAN'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :device The value to assign to the {OCI::Core::Models::AttachVolumeDetails#device #device} proprety
# @option attributes [String] :display_name The value to assign to the {OCI::Core::Models::AttachVolumeDetails#display_name #display_name} proprety
# @option attributes [String] :instance_id The value to assign to the {OCI::Core::Models::AttachVolumeDetails#instance_id #instance_id} proprety
# @option attributes [BOOLEAN] :is_read_only The value to assign to the {OCI::Core::Models::AttachVolumeDetails#is_read_only #is_read_only} proprety
# @option attributes [String] :volume_id The value to assign to the {OCI::Core::Models::AttachVolumeDetails#volume_id #volume_id} proprety
# @option attributes [BOOLEAN] :is_pv_encryption_in_transit_enabled The value to assign to the {#is_pv_encryption_in_transit_enabled} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
attributes['type'] = 'paravirtualized'
super(attributes)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.is_pv_encryption_in_transit_enabled = attributes[:'isPvEncryptionInTransitEnabled'] unless attributes[:'isPvEncryptionInTransitEnabled'].nil?
raise 'You cannot provide both :isPvEncryptionInTransitEnabled and :is_pv_encryption_in_transit_enabled' if attributes.key?(:'isPvEncryptionInTransitEnabled') && attributes.key?(:'is_pv_encryption_in_transit_enabled')
self.is_pv_encryption_in_transit_enabled = attributes[:'is_pv_encryption_in_transit_enabled'] unless attributes[:'is_pv_encryption_in_transit_enabled'].nil?
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
device == other.device &&
display_name == other.display_name &&
instance_id == other.instance_id &&
is_read_only == other.is_read_only &&
type == other.type &&
volume_id == other.volume_id &&
is_pv_encryption_in_transit_enabled == other.is_pv_encryption_in_transit_enabled
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[device, display_name, instance_id, is_read_only, type, volume_id, is_pv_encryption_in_transit_enabled].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 39.945055 | 223 | 0.692022 |
e9ae6eab91792ce474ae05a2d6b27b2083422c46 | 13,493 | require 'test_helper'
class BootstrapCheckboxTest < ActionView::TestCase
include BootstrapForm::Helper
def setup
setup_test_fixture
end
test "check_box is wrapped correctly" do
expected = %{<div class="checkbox"><label for="user_terms"><input name="user[terms]" type="hidden" value="0" /><input id="user_terms" name="user[terms]" type="checkbox" value="1" /> I agree to the terms</label></div>}
assert_equal expected, @builder.check_box(:terms, label: 'I agree to the terms')
end
test "disabled check_box has proper wrapper classes" do
expected = %{<div class="checkbox disabled"><label for="user_terms"><input disabled="disabled" name="user[terms]" type="hidden" value="0" /><input disabled="disabled" id="user_terms" name="user[terms]" type="checkbox" value="1" /> I agree to the terms</label></div>}
assert_equal expected, @builder.check_box(:terms, label: 'I agree to the terms', disabled: true)
end
test "check_box label allows html" do
expected = %{<div class="checkbox"><label for="user_terms"><input name="user[terms]" type="hidden" value="0" /><input id="user_terms" name="user[terms]" type="checkbox" value="1" /> I agree to the <a href="#">terms</a></label></div>}
assert_equal expected, @builder.check_box(:terms, label: %{I agree to the <a href="#">terms</a>}.html_safe)
end
test "check_box accepts a block to define the label" do
expected = %{<div class="checkbox"><label for="user_terms"><input name="user[terms]" type="hidden" value="0" /><input id="user_terms" name="user[terms]" type="checkbox" value="1" /> I agree to the terms</label></div>}
assert_equal expected, @builder.check_box(:terms) { "I agree to the terms" }
end
test "check_box accepts a custom label class" do
expected = %{<div class="checkbox"><label class="btn" for="user_terms"><input name="user[terms]" type="hidden" value="0" /><input id="user_terms" name="user[terms]" type="checkbox" value="1" /> Terms</label></div>}
assert_equal expected, @builder.check_box(:terms, label_class: 'btn')
end
test "check_box responds to checked_value and unchecked_value arguments" do
expected = %{<div class="checkbox"><label for="user_terms"><input name="user[terms]" type="hidden" value="no" /><input id="user_terms" name="user[terms]" type="checkbox" value="yes" /> I agree to the terms</label></div>}
assert_equal expected, @builder.check_box(:terms, {label: 'I agree to the terms'}, 'yes', 'no')
end
test "inline checkboxes" do
expected = %{<label class="checkbox-inline" for="user_terms"><input name="user[terms]" type="hidden" value="0" /><input id="user_terms" name="user[terms]" type="checkbox" value="1" /> I agree to the terms</label>}
assert_equal expected, @builder.check_box(:terms, label: 'I agree to the terms', inline: true)
end
test "disabled inline check_box" do
expected = %{<label class="checkbox-inline disabled" for="user_terms"><input disabled="disabled" name="user[terms]" type="hidden" value="0" /><input disabled="disabled" id="user_terms" name="user[terms]" type="checkbox" value="1" /> I agree to the terms</label>}
assert_equal expected, @builder.check_box(:terms, label: 'I agree to the terms', inline: true, disabled: true)
end
test "inline checkboxes with custom label class" do
expected = %{<label class="checkbox-inline btn" for="user_terms"><input name="user[terms]" type="hidden" value="0" /><input id="user_terms" name="user[terms]" type="checkbox" value="1" /> Terms</label>}
assert_equal expected, @builder.check_box(:terms, inline: true, label_class: 'btn')
end
test 'collection_check_boxes renders the form_group correctly' do
collection = [Address.new(id: 1, street: 'Foobar')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">This is a checkbox collection</label><div class="checkbox"><label for="user_misc_1"><input id="user_misc_1" name="user[misc][]" type="checkbox" value="1" /> Foobar</label></div><span class="help-block">With a help!</span></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, :street, label: 'This is a checkbox collection', help: 'With a help!')
end
test 'collection_check_boxes renders multiple checkboxes correctly' do
collection = [Address.new(id: 1, street: 'Foo'), Address.new(id: 2, street: 'Bar')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">Misc</label><div class="checkbox"><label for="user_misc_1"><input id="user_misc_1" name="user[misc][]" type="checkbox" value="1" /> Foo</label></div><div class="checkbox"><label for="user_misc_2"><input id="user_misc_2" name="user[misc][]" type="checkbox" value="2" /> Bar</label></div></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, :street)
end
test 'collection_check_boxes renders inline checkboxes correctly' do
collection = [Address.new(id: 1, street: 'Foo'), Address.new(id: 2, street: 'Bar')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">Misc</label><label class="checkbox-inline" for="user_misc_1"><input id="user_misc_1" name="user[misc][]" type="checkbox" value="1" /> Foo</label><label class="checkbox-inline" for="user_misc_2"><input id="user_misc_2" name="user[misc][]" type="checkbox" value="2" /> Bar</label></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, :street, inline: true)
end
test 'collection_check_boxes renders with checked option correctly' do
collection = [Address.new(id: 1, street: 'Foo'), Address.new(id: 2, street: 'Bar')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">Misc</label><div class="checkbox"><label for="user_misc_1"><input checked="checked" id="user_misc_1" name="user[misc][]" type="checkbox" value="1" /> Foo</label></div><div class="checkbox"><label for="user_misc_2"><input id="user_misc_2" name="user[misc][]" type="checkbox" value="2" /> Bar</label></div></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, :street, checked: 1)
assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, :street, checked: collection.first)
end
test 'collection_check_boxes renders with multiple checked options correctly' do
collection = [Address.new(id: 1, street: 'Foo'), Address.new(id: 2, street: 'Bar')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">Misc</label><div class="checkbox"><label for="user_misc_1"><input checked="checked" id="user_misc_1" name="user[misc][]" type="checkbox" value="1" /> Foo</label></div><div class="checkbox"><label for="user_misc_2"><input checked="checked" id="user_misc_2" name="user[misc][]" type="checkbox" value="2" /> Bar</label></div></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, :street, checked: [1, 2])
assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, :street, checked: collection)
end
test 'collection_check_boxes sanitizes values when generating label `for`' do
collection = [Address.new(id: 1, street: 'Foo St')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">Misc</label><div class="checkbox"><label for="user_misc_foo_st"><input id="user_misc_foo_st" name="user[misc][]" type="checkbox" value="Foo St" /> Foo St</label></div></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, :street, :street)
end
test 'collection_check_boxes renders multiple checkboxes with labels defined by Proc :text_method correctly' do
collection = [Address.new(id: 1, street: 'Foo'), Address.new(id: 2, street: 'Bar')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">Misc</label><div class="checkbox"><label for="user_misc_1"><input id="user_misc_1" name="user[misc][]" type="checkbox" value="1" /> ooF</label></div><div class="checkbox"><label for="user_misc_2"><input id="user_misc_2" name="user[misc][]" type="checkbox" value="2" /> raB</label></div></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, Proc.new { |a| a.street.reverse })
end
test 'collection_check_boxes renders multiple checkboxes with values defined by Proc :value_method correctly' do
collection = [Address.new(id: 1, street: 'Foo'), Address.new(id: 2, street: 'Bar')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">Misc</label><div class="checkbox"><label for="user_misc_address_1"><input id="user_misc_address_1" name="user[misc][]" type="checkbox" value="address_1" /> Foo</label></div><div class="checkbox"><label for="user_misc_address_2"><input id="user_misc_address_2" name="user[misc][]" type="checkbox" value="address_2" /> Bar</label></div></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, Proc.new { |a| "address_#{a.id}" }, :street)
end
test 'collection_check_boxes renders multiple checkboxes with labels defined by lambda :text_method correctly' do
collection = [Address.new(id: 1, street: 'Foo'), Address.new(id: 2, street: 'Bar')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">Misc</label><div class="checkbox"><label for="user_misc_1"><input id="user_misc_1" name="user[misc][]" type="checkbox" value="1" /> ooF</label></div><div class="checkbox"><label for="user_misc_2"><input id="user_misc_2" name="user[misc][]" type="checkbox" value="2" /> raB</label></div></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, lambda { |a| a.street.reverse })
end
test 'collection_check_boxes renders multiple checkboxes with values defined by lambda :value_method correctly' do
collection = [Address.new(id: 1, street: 'Foo'), Address.new(id: 2, street: 'Bar')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">Misc</label><div class="checkbox"><label for="user_misc_address_1"><input id="user_misc_address_1" name="user[misc][]" type="checkbox" value="address_1" /> Foo</label></div><div class="checkbox"><label for="user_misc_address_2"><input id="user_misc_address_2" name="user[misc][]" type="checkbox" value="address_2" /> Bar</label></div></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, lambda { |a| "address_#{a.id}" }, :street)
end
test 'collection_check_boxes renders with checked option correctly with Proc :value_method' do
collection = [Address.new(id: 1, street: 'Foo'), Address.new(id: 2, street: 'Bar')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">Misc</label><div class="checkbox"><label for="user_misc_address_1"><input checked="checked" id="user_misc_address_1" name="user[misc][]" type="checkbox" value="address_1" /> Foo</label></div><div class="checkbox"><label for="user_misc_address_2"><input id="user_misc_address_2" name="user[misc][]" type="checkbox" value="address_2" /> Bar</label></div></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, Proc.new { |a| "address_#{a.id}" }, :street, checked: "address_1")
assert_equal expected, @builder.collection_check_boxes(:misc, collection, Proc.new { |a| "address_#{a.id}" }, :street, checked: collection.first)
end
test 'collection_check_boxes renders with multiple checked options correctly with lambda :value_method' do
collection = [Address.new(id: 1, street: 'Foo'), Address.new(id: 2, street: 'Bar')]
expected = %{<input id="user_misc" multiple="multiple" name="user[misc][]" type="hidden" value="" /><div class="form-group"><label class="control-label" for="user_misc">Misc</label><div class="checkbox"><label for="user_misc_address_1"><input checked="checked" id="user_misc_address_1" name="user[misc][]" type="checkbox" value="address_1" /> Foo</label></div><div class="checkbox"><label for="user_misc_address_2"><input checked="checked" id="user_misc_address_2" name="user[misc][]" type="checkbox" value="address_2" /> Bar</label></div></div>}
assert_equal expected, @builder.collection_check_boxes(:misc, collection, lambda { |a| "address_#{a.id}" }, :street, checked: ["address_1", "address_2"])
assert_equal expected, @builder.collection_check_boxes(:misc, collection, lambda { |a| "address_#{a.id}" }, :street, checked: collection)
end
end
| 93.055172 | 550 | 0.706811 |
217029341cef72ba8e802c8c8c6cd84c4e80d4a6 | 120 | class BuildController < ApplicationController
layout "build"
def about
end
def garage
end
end
| 10 | 45 | 0.65 |
f8153c9f3da424200fbde52b2ea525d889bcce15 | 2,036 | require 'spec_helper'
RSpec.describe Circuitry::CLI do
subject { described_class }
describe '#provision' do
before do
allow(Circuitry::Provisioning::QueueCreator).to receive(:find_or_create).and_return(queue)
allow(Circuitry::Provisioning::TopicCreator).to receive(:find_or_create).and_return(topic)
allow(Circuitry::Provisioning::SubscriptionCreator).to receive(:subscribe_all).and_return(true)
subject.start(command.split)
end
let(:queue) { Circuitry::Queue.new('http://sqs.amazontest.com/example') }
let(:topic) { Circuitry::Topic.new('arn:aws:sns:us-east-1:123456789012:some-topic-name') }
describe 'vanilla command' do
let(:command) { 'provision example -t topic1 topic2 -a 123 -s 123 -r us-east-1 -n 7' }
it 'creates primary and dead letter queues' do
expect(Circuitry::Provisioning::QueueCreator).to have_received(:find_or_create).once.with('example', hash_including(dead_letter_queue_name: 'example-failures'))
end
it 'creates each topic' do
expect(Circuitry::Provisioning::TopicCreator).to have_received(:find_or_create).twice
end
it 'subscribes to all topics' do
expect(Circuitry::Provisioning::SubscriptionCreator).to have_received(:subscribe_all).once.with(queue, [topic, topic])
end
it 'configures max_receive_count' do
expect(Circuitry.subscriber_config.max_receive_count).to eql(7)
end
end
describe 'no queue given' do
let(:command) { 'provision' }
it 'does nothing' do
expect(Circuitry::Provisioning::QueueCreator).to_not have_received(:find_or_create)
end
end
describe 'no topics given' do
let(:command) { 'provision example' }
it 'does not create queue' do
expect(Circuitry::Provisioning::QueueCreator).to_not have_received(:find_or_create)
end
it 'does not create topics' do
expect(Circuitry::Provisioning::TopicCreator).to_not have_received(:find_or_create)
end
end
end
end
| 34.508475 | 168 | 0.700884 |
1a3bcb2ee7b9d3bfaf56bf6f9408cb7e4771220a | 851 | module Selenium
module WebDriver
module IPhone
class Bridge < Remote::Bridge
DEFAULT_URL = "http://#{Platform.localhost}:3001/hub/"
def initialize(opts = {})
remote_opts = {
:url => opts.fetch(:url, DEFAULT_URL),
:desired_capabilities => opts.fetch(:desired_capabilities, capabilities),
:http_client => opts[:http_client]
}
super remote_opts
end
def browser
:iphone
end
def driver_extensions
[
DriverExtensions::TakesScreenshot,
DriverExtensions::HasInputDevices
]
end
def capabilities
@capabilities ||= Remote::Capabilities.iphone
end
end # Bridge
end # IPhone
end # WebDriver
end # Selenium | 23.638889 | 85 | 0.542891 |
e8b5b29349bf429503e7ec34635000b795205bf7 | 2,593 | cask "stm32cubemx" do
module Utils
def self.cubemx_app_path
"/Applications/STMicroelectronics/STM32CubeMX.app"
end
def self.usr_local_bin_file
"/usr/local/bin/stm32cubemx"
end
def self.cubemx_script_file
"#{cubemx_app_path}/Contents/MacOs/stm32cubemx.sh"
end
end
version "6.2.0"
sha256 :no_check
url "https://www.dropbox.com/s/oega5zar68w8b0p/en.stm32cubemx_v6.2.0.zip?dl=1", header: "", data: "",
verified: "dropbox.com/s/oega5zar68w8b0p"
name "STM32CubeMX"
desc "STM32Cube initialization code generator"
homepage "https://www.st.com/en/development-tools/stm32cubemx.html"
auto_updates false
depends_on cask: "AdoptOpenJDK/openjdk/adoptopenjdk15"
installer script: {
executable: "/Library/Java/JavaVirtualMachines/adoptopenjdk-15.jdk/Contents/Home/bin/java",
args: ["-jar", "#{staged_path}/SetupSTM32CubeMX-6.2.0-RC3.app/Contents/MacOs/SetupSTM32CubeMX-6_2_0"],
must_succeed: true,
}
postflight do
ohai "Creating command line invocation script"
File.open(Utils.cubemx_script_file, "w") do |f|
f << "\#\!/usr/bin/env bash\n"
f << "/Library/Java/JavaVirtualMachines/adoptopenjdk-15.jdk/Contents/Home/bin/java "
f << "-jar "
f << "/Applications/STMicroelectronics/STM32CubeMX.app/Contents/MacOS/STM32CubeMX $@\n"
f.close
end
ohai "Symlinking command line invocation script to /usr/local/bin"
FileUtils.chmod 0755, Utils.cubemx_script_file
FileUtils.ln_sf Utils.cubemx_script_file, Utils.usr_local_bin_file
ohai "Fixing STM32CubeMX.app finder opening issue"
FileUtils.ln_sf "#{staged_path}/jre", "/Applications/STMicroelectronics/STM32CubeMX.app/Contents/MacOs/jre"
end
uninstall_preflight do
FileUtils.rm Utils.usr_local_bin_file, force: true
end
uninstall script: {
executable: "/Library/Java/JavaVirtualMachines/adoptopenjdk-15.jdk/Contents/Home/bin/java",
args: ["-jar", "#{Utils.cubemx_app_path}/Contents/Resources/Uninstaller/uninstaller.jar"],
must_succeed: false,
}
caveats "This cask depends on OpenJDK 15 and does **not** work with OpenJDK 16.\n" \
"To use, first install OpenJDK 15:\n" \
" $ brew install --cask AdoptOpenJDK/openjdk/adoptopenjdk15\n" \
"The STM32CubeMX.app might not work when trying to open it from the Finder.\n" \
"If it's the case, launch the app from the terminal by running:\n" \
" $ stm32cubemx\n" \
"Or with '-i' option for the interactive mode:\n" \
" $ stm32cubemx -i\n" \
end
| 36.521127 | 114 | 0.693405 |
017b28a2a73ccdfce99531bba08001a88f008f12 | 329 | namespace :db do
desc "Describe all the tables in the database by reading the table comments"
task :comments => :environment do
ActiveRecord::Base.connection.tables.sort.each do |table_name|
comment = ActiveRecord::Base.connection.table_comment(table_name)
puts "#{table_name} - #{comment}"
end
end
end
| 32.9 | 78 | 0.723404 |
7a5d30999f352cecd6c14a552322f950615d2d8c | 1,259 | # frozen_string_literal: true
require 'bundler/setup'
# require 'simplecov'
# SimpleCov.start
require 'minitest/pride'
require 'minitest/autorun'
require_relative 'helpers/memcached'
ENV['SASL_CONF_PATH'] = "#{File.dirname(__FILE__)}/sasl/memcached.conf"
require 'dalli'
require 'logger'
require 'ostruct'
require 'securerandom'
Dalli.logger = Logger.new($stdout)
Dalli.logger.level = Logger::ERROR
module MiniTest
class Spec
include Memcached::Helper
def assert_error(error, regexp = nil, &block)
ex = assert_raises(error, &block)
assert_match(regexp, ex.message, "#{ex.class.name}: #{ex.message}\n#{ex.backtrace.join("\n\t")}")
end
def op_cas_succeeds(rsp)
rsp.is_a?(Integer) && rsp.positive?
end
def op_replace_succeeds(rsp)
rsp.is_a?(Integer) && rsp.positive?
end
# add and set must have the same return value because of DalliStore#write_entry
def op_addset_succeeds(rsp)
rsp.is_a?(Integer) && rsp.positive?
end
def with_connectionpool
require 'connection_pool'
yield
end
def with_nil_logger
old = Dalli.logger
Dalli.logger = Logger.new(nil)
begin
yield
ensure
Dalli.logger = old
end
end
end
end
| 21.706897 | 103 | 0.676728 |
1122b93dd7cabea3ae67b2c075b6c31beb64f606 | 405 | cask 'lastfm' do
version '2.1.37'
sha256 'dc46e58111f8555fc0b1d6d2bd11e8fd4e4c45c6c7e953d106e07be8d6d8b448'
url "https://cdn.last.fm/client/Mac/Last.fm-#{version}.zip"
appcast 'https://cdn.last.fm/client/Mac/updates.xml',
checkpoint: '7a9b0239c6af0128a3eff20c46c3893cee1f3a57786f6c2fca8a8df8e8993280'
name 'Last.fm Scrobbler'
homepage 'http://www.last.fm/'
app 'Last.fm.app'
end
| 31.153846 | 88 | 0.750617 |
7aec0284cee69118ffb820439131a03be2b850b4 | 47,697 | # frozen_string_literal: true
# Copyright 2021 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.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "google/cloud/errors"
require "google/cloud/memcache/v1/cloud_memcache_pb"
module Google
module Cloud
module Memcache
module V1
module CloudMemcache
##
# Client for the CloudMemcache service.
#
# Configures and manages Cloud Memorystore for Memcached instances.
#
#
# The `memcache.googleapis.com` service implements the Google Cloud Memorystore
# for Memcached API and defines the following resource model for managing
# Memorystore Memcached (also called Memcached below) instances:
# * The service works with a collection of cloud projects, named: `/projects/*`
# * Each project has a collection of available locations, named: `/locations/*`
# * Each location has a collection of Memcached instances, named:
# `/instances/*`
# * As such, Memcached instances are resources of the form:
# `/projects/{project_id}/locations/{location_id}/instances/{instance_id}`
#
# Note that location_id must be a GCP `region`; for example:
# * `projects/my-memcached-project/locations/us-central1/instances/my-memcached`
#
class Client
include Paths
# @private
attr_reader :cloud_memcache_stub
##
# Configure the CloudMemcache Client class.
#
# See {::Google::Cloud::Memcache::V1::CloudMemcache::Client::Configuration}
# for a description of the configuration fields.
#
# ## Example
#
# To modify the configuration for all CloudMemcache clients:
#
# ::Google::Cloud::Memcache::V1::CloudMemcache::Client.configure do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def self.configure
@configure ||= begin
namespace = ["Google", "Cloud", "Memcache", "V1"]
parent_config = while namespace.any?
parent_name = namespace.join "::"
parent_const = const_get parent_name
break parent_const.configure if parent_const.respond_to? :configure
namespace.pop
end
default_config = Client::Configuration.new parent_config
default_config.rpcs.list_instances.timeout = 1200.0
default_config.rpcs.get_instance.timeout = 1200.0
default_config.rpcs.create_instance.timeout = 1200.0
default_config.rpcs.update_instance.timeout = 1200.0
default_config.rpcs.update_parameters.timeout = 1200.0
default_config.rpcs.delete_instance.timeout = 1200.0
default_config.rpcs.apply_parameters.timeout = 1200.0
default_config
end
yield @configure if block_given?
@configure
end
##
# Configure the CloudMemcache Client instance.
#
# The configuration is set to the derived mode, meaning that values can be changed,
# but structural changes (adding new fields, etc.) are not allowed. Structural changes
# should be made on {Client.configure}.
#
# See {::Google::Cloud::Memcache::V1::CloudMemcache::Client::Configuration}
# for a description of the configuration fields.
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def configure
yield @config if block_given?
@config
end
##
# Create a new CloudMemcache client object.
#
# ## Examples
#
# To create a new CloudMemcache client with the default
# configuration:
#
# client = ::Google::Cloud::Memcache::V1::CloudMemcache::Client.new
#
# To create a new CloudMemcache client with a custom
# configuration:
#
# client = ::Google::Cloud::Memcache::V1::CloudMemcache::Client.new do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the CloudMemcache client.
# @yieldparam config [Client::Configuration]
#
def initialize
# These require statements are intentionally placed here to initialize
# the gRPC module only when it's required.
# See https://github.com/googleapis/toolkit/issues/446
require "gapic/grpc"
require "google/cloud/memcache/v1/cloud_memcache_services_pb"
# Create the configuration object
@config = Configuration.new Client.configure
# Yield the configuration if needed
yield @config if block_given?
# Create credentials
credentials = @config.credentials
# Use self-signed JWT if the scope and endpoint are unchanged from default,
# but only if the default endpoint does not have a region prefix.
enable_self_signed_jwt = @config.scope == Client.configure.scope &&
@config.endpoint == Client.configure.endpoint &&
[email protected](".").first.include?("-")
credentials ||= Credentials.default scope: @config.scope,
enable_self_signed_jwt: enable_self_signed_jwt
if credentials.is_a?(String) || credentials.is_a?(Hash)
credentials = Credentials.new credentials, scope: @config.scope
end
@quota_project_id = @config.quota_project
@quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id
@operations_client = Operations.new do |config|
config.credentials = credentials
config.endpoint = @config.endpoint
end
@cloud_memcache_stub = ::Gapic::ServiceStub.new(
::Google::Cloud::Memcache::V1::CloudMemcache::Stub,
credentials: credentials,
endpoint: @config.endpoint,
channel_args: @config.channel_args,
interceptors: @config.interceptors
)
end
##
# Get the associated client for long-running operations.
#
# @return [::Google::Cloud::Memcache::V1::CloudMemcache::Operations]
#
attr_reader :operations_client
# Service calls
##
# Lists Instances in a given location.
#
# @overload list_instances(request, options = nil)
# Pass arguments to `list_instances` via a request object, either of type
# {::Google::Cloud::Memcache::V1::ListInstancesRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Memcache::V1::ListInstancesRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload list_instances(parent: nil, page_size: nil, page_token: nil, filter: nil, order_by: nil)
# Pass arguments to `list_instances` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. The resource name of the instance location using the form:
# `projects/{project_id}/locations/{location_id}`
# where `location_id` refers to a GCP region
# @param page_size [::Integer]
# The maximum number of items to return.
#
# If not specified, a default value of 1000 will be used by the service.
# Regardless of the page_size value, the response may include a partial list
# and a caller should only rely on response's
# [next_page_token][CloudMemcache.ListInstancesResponse.next_page_token]
# to determine if there are more instances left to be queried.
# @param page_token [::String]
# The next_page_token value returned from a previous List request,
# if any.
# @param filter [::String]
# List filter. For example, exclude all Memcached instances with name as
# my-instance by specifying "name != my-instance".
# @param order_by [::String]
# Sort results. Supported values are "name", "name desc" or "" (unsorted).
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::PagedEnumerable<::Google::Cloud::Memcache::V1::Instance>]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::PagedEnumerable<::Google::Cloud::Memcache::V1::Instance>]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def list_instances request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Memcache::V1::ListInstancesRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.list_instances.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Memcache::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"parent" => request.parent
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.list_instances.timeout,
metadata: metadata,
retry_policy: @config.rpcs.list_instances.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@cloud_memcache_stub.call_rpc :list_instances, request, options: options do |response, operation|
response = ::Gapic::PagedEnumerable.new @cloud_memcache_stub, :list_instances, request, response, operation, options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Gets details of a single Instance.
#
# @overload get_instance(request, options = nil)
# Pass arguments to `get_instance` via a request object, either of type
# {::Google::Cloud::Memcache::V1::GetInstanceRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Memcache::V1::GetInstanceRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload get_instance(name: nil)
# Pass arguments to `get_instance` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Memcached instance resource name in the format:
# `projects/{project_id}/locations/{location_id}/instances/{instance_id}`
# where `location_id` refers to a GCP region
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Google::Cloud::Memcache::V1::Instance]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Google::Cloud::Memcache::V1::Instance]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def get_instance request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Memcache::V1::GetInstanceRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.get_instance.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Memcache::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.get_instance.timeout,
metadata: metadata,
retry_policy: @config.rpcs.get_instance.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@cloud_memcache_stub.call_rpc :get_instance, request, options: options do |response, operation|
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Creates a new Instance in a given location.
#
# @overload create_instance(request, options = nil)
# Pass arguments to `create_instance` via a request object, either of type
# {::Google::Cloud::Memcache::V1::CreateInstanceRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Memcache::V1::CreateInstanceRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload create_instance(parent: nil, instance_id: nil, instance: nil)
# Pass arguments to `create_instance` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. The resource name of the instance location using the form:
# `projects/{project_id}/locations/{location_id}`
# where `location_id` refers to a GCP region
# @param instance_id [::String]
# Required. The logical name of the Memcached instance in the user
# project with the following restrictions:
#
# * Must contain only lowercase letters, numbers, and hyphens.
# * Must start with a letter.
# * Must be between 1-40 characters.
# * Must end with a number or a letter.
# * Must be unique within the user project / location
#
# If any of the above are not met, will raise an invalid argument error.
# @param instance [::Google::Cloud::Memcache::V1::Instance, ::Hash]
# Required. A Memcached Instance
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def create_instance request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Memcache::V1::CreateInstanceRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.create_instance.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Memcache::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"parent" => request.parent
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.create_instance.timeout,
metadata: metadata,
retry_policy: @config.rpcs.create_instance.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@cloud_memcache_stub.call_rpc :create_instance, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Updates an existing Instance in a given project and location.
#
# @overload update_instance(request, options = nil)
# Pass arguments to `update_instance` via a request object, either of type
# {::Google::Cloud::Memcache::V1::UpdateInstanceRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Memcache::V1::UpdateInstanceRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload update_instance(update_mask: nil, instance: nil)
# Pass arguments to `update_instance` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param update_mask [::Google::Protobuf::FieldMask, ::Hash]
# Required. Mask of fields to update.
# * `displayName`
# @param instance [::Google::Cloud::Memcache::V1::Instance, ::Hash]
# Required. A Memcached Instance.
# Only fields specified in update_mask are updated.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def update_instance request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Memcache::V1::UpdateInstanceRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.update_instance.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Memcache::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"instance.name" => request.instance.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.update_instance.timeout,
metadata: metadata,
retry_policy: @config.rpcs.update_instance.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@cloud_memcache_stub.call_rpc :update_instance, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Updates the defined Memcached Parameters for an existing Instance.
# This method only stages the parameters, it must be followed by
# ApplyParameters to apply the parameters to nodes of the Memcached Instance.
#
# @overload update_parameters(request, options = nil)
# Pass arguments to `update_parameters` via a request object, either of type
# {::Google::Cloud::Memcache::V1::UpdateParametersRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Memcache::V1::UpdateParametersRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload update_parameters(name: nil, update_mask: nil, parameters: nil)
# Pass arguments to `update_parameters` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Resource name of the Memcached instance for which the parameters should be
# updated.
# @param update_mask [::Google::Protobuf::FieldMask, ::Hash]
# Required. Mask of fields to update.
# @param parameters [::Google::Cloud::Memcache::V1::MemcacheParameters, ::Hash]
# The parameters to apply to the instance.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def update_parameters request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Memcache::V1::UpdateParametersRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.update_parameters.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Memcache::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.update_parameters.timeout,
metadata: metadata,
retry_policy: @config.rpcs.update_parameters.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@cloud_memcache_stub.call_rpc :update_parameters, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Deletes a single Instance.
#
# @overload delete_instance(request, options = nil)
# Pass arguments to `delete_instance` via a request object, either of type
# {::Google::Cloud::Memcache::V1::DeleteInstanceRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Memcache::V1::DeleteInstanceRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload delete_instance(name: nil)
# Pass arguments to `delete_instance` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Memcached instance resource name in the format:
# `projects/{project_id}/locations/{location_id}/instances/{instance_id}`
# where `location_id` refers to a GCP region
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def delete_instance request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Memcache::V1::DeleteInstanceRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.delete_instance.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Memcache::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.delete_instance.timeout,
metadata: metadata,
retry_policy: @config.rpcs.delete_instance.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@cloud_memcache_stub.call_rpc :delete_instance, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# ApplyParameters will restart the set of specified nodes in order to update
# them to the current set of parameters for the Memcached Instance.
#
# @overload apply_parameters(request, options = nil)
# Pass arguments to `apply_parameters` via a request object, either of type
# {::Google::Cloud::Memcache::V1::ApplyParametersRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Memcache::V1::ApplyParametersRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload apply_parameters(name: nil, node_ids: nil, apply_all: nil)
# Pass arguments to `apply_parameters` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Resource name of the Memcached instance for which parameter group updates
# should be applied.
# @param node_ids [::Array<::String>]
# Nodes to which we should apply the instance-level parameter group.
# @param apply_all [::Boolean]
# Whether to apply instance-level parameter group to all nodes. If set to
# true, will explicitly restrict users from specifying any nodes, and apply
# parameter group updates to all nodes within the instance.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def apply_parameters request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Memcache::V1::ApplyParametersRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.apply_parameters.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Memcache::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.apply_parameters.timeout,
metadata: metadata,
retry_policy: @config.rpcs.apply_parameters.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@cloud_memcache_stub.call_rpc :apply_parameters, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Configuration class for the CloudMemcache API.
#
# This class represents the configuration for CloudMemcache,
# providing control over timeouts, retry behavior, logging, transport
# parameters, and other low-level controls. Certain parameters can also be
# applied individually to specific RPCs. See
# {::Google::Cloud::Memcache::V1::CloudMemcache::Client::Configuration::Rpcs}
# for a list of RPCs that can be configured independently.
#
# Configuration can be applied globally to all clients, or to a single client
# on construction.
#
# # Examples
#
# To modify the global config, setting the timeout for list_instances
# to 20 seconds, and all remaining timeouts to 10 seconds:
#
# ::Google::Cloud::Memcache::V1::CloudMemcache::Client.configure do |config|
# config.timeout = 10.0
# config.rpcs.list_instances.timeout = 20.0
# end
#
# To apply the above configuration only to a new client:
#
# client = ::Google::Cloud::Memcache::V1::CloudMemcache::Client.new do |config|
# config.timeout = 10.0
# config.rpcs.list_instances.timeout = 20.0
# end
#
# @!attribute [rw] endpoint
# The hostname or hostname:port of the service endpoint.
# Defaults to `"memcache.googleapis.com"`.
# @return [::String]
# @!attribute [rw] credentials
# Credentials to send with calls. You may provide any of the following types:
# * (`String`) The path to a service account key file in JSON format
# * (`Hash`) A service account key as a Hash
# * (`Google::Auth::Credentials`) A googleauth credentials object
# (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html))
# * (`Signet::OAuth2::Client`) A signet oauth2 client object
# (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html))
# * (`GRPC::Core::Channel`) a gRPC channel with included credentials
# * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object
# * (`nil`) indicating no credentials
# @return [::Object]
# @!attribute [rw] scope
# The OAuth scopes
# @return [::Array<::String>]
# @!attribute [rw] lib_name
# The library name as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] lib_version
# The library version as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] channel_args
# Extra parameters passed to the gRPC channel. Note: this is ignored if a
# `GRPC::Core::Channel` object is provided as the credential.
# @return [::Hash]
# @!attribute [rw] interceptors
# An array of interceptors that are run before calls are executed.
# @return [::Array<::GRPC::ClientInterceptor>]
# @!attribute [rw] timeout
# The call timeout in seconds.
# @return [::Numeric]
# @!attribute [rw] metadata
# Additional gRPC headers to be sent with the call.
# @return [::Hash{::Symbol=>::String}]
# @!attribute [rw] retry_policy
# The retry policy. The value is a hash with the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
# @return [::Hash]
# @!attribute [rw] quota_project
# A separate project against which to charge quota.
# @return [::String]
#
class Configuration
extend ::Gapic::Config
config_attr :endpoint, "memcache.googleapis.com", ::String
config_attr :credentials, nil do |value|
allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil]
allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC
allowed.any? { |klass| klass === value }
end
config_attr :scope, nil, ::String, ::Array, nil
config_attr :lib_name, nil, ::String, nil
config_attr :lib_version, nil, ::String, nil
config_attr(:channel_args, { "grpc.service_config_disable_resolution" => 1 }, ::Hash, nil)
config_attr :interceptors, nil, ::Array, nil
config_attr :timeout, nil, ::Numeric, nil
config_attr :metadata, nil, ::Hash, nil
config_attr :retry_policy, nil, ::Hash, ::Proc, nil
config_attr :quota_project, nil, ::String, nil
# @private
def initialize parent_config = nil
@parent_config = parent_config unless parent_config.nil?
yield self if block_given?
end
##
# Configurations for individual RPCs
# @return [Rpcs]
#
def rpcs
@rpcs ||= begin
parent_rpcs = nil
parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config.respond_to?(:rpcs)
Rpcs.new parent_rpcs
end
end
##
# Configuration RPC class for the CloudMemcache API.
#
# Includes fields providing the configuration for each RPC in this service.
# Each configuration object is of type `Gapic::Config::Method` and includes
# the following configuration fields:
#
# * `timeout` (*type:* `Numeric`) - The call timeout in seconds
# * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers
# * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields
# include the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
#
class Rpcs
##
# RPC-specific configuration for `list_instances`
# @return [::Gapic::Config::Method]
#
attr_reader :list_instances
##
# RPC-specific configuration for `get_instance`
# @return [::Gapic::Config::Method]
#
attr_reader :get_instance
##
# RPC-specific configuration for `create_instance`
# @return [::Gapic::Config::Method]
#
attr_reader :create_instance
##
# RPC-specific configuration for `update_instance`
# @return [::Gapic::Config::Method]
#
attr_reader :update_instance
##
# RPC-specific configuration for `update_parameters`
# @return [::Gapic::Config::Method]
#
attr_reader :update_parameters
##
# RPC-specific configuration for `delete_instance`
# @return [::Gapic::Config::Method]
#
attr_reader :delete_instance
##
# RPC-specific configuration for `apply_parameters`
# @return [::Gapic::Config::Method]
#
attr_reader :apply_parameters
# @private
def initialize parent_rpcs = nil
list_instances_config = parent_rpcs.list_instances if parent_rpcs.respond_to? :list_instances
@list_instances = ::Gapic::Config::Method.new list_instances_config
get_instance_config = parent_rpcs.get_instance if parent_rpcs.respond_to? :get_instance
@get_instance = ::Gapic::Config::Method.new get_instance_config
create_instance_config = parent_rpcs.create_instance if parent_rpcs.respond_to? :create_instance
@create_instance = ::Gapic::Config::Method.new create_instance_config
update_instance_config = parent_rpcs.update_instance if parent_rpcs.respond_to? :update_instance
@update_instance = ::Gapic::Config::Method.new update_instance_config
update_parameters_config = parent_rpcs.update_parameters if parent_rpcs.respond_to? :update_parameters
@update_parameters = ::Gapic::Config::Method.new update_parameters_config
delete_instance_config = parent_rpcs.delete_instance if parent_rpcs.respond_to? :delete_instance
@delete_instance = ::Gapic::Config::Method.new delete_instance_config
apply_parameters_config = parent_rpcs.apply_parameters if parent_rpcs.respond_to? :apply_parameters
@apply_parameters = ::Gapic::Config::Method.new apply_parameters_config
yield self if block_given?
end
end
end
end
end
end
end
end
end
| 52.070961 | 132 | 0.567813 |
08224f489964748613441ff9ca0cd499aea5856f | 3,989 | require 'spec_helper'
require_relative './shared_context'
describe Fog::Network::OpenStack do
before :all do
openstack_vcr = OpenStackVCR.new(
:vcr_directory => 'spec/fixtures/openstack/network',
:service_class => Fog::Network::OpenStack,
:project_scoped => true
)
@service = openstack_vcr.service
@current_project = openstack_vcr.project_name
openstack_vcr = OpenStackVCR.new(
:vcr_directory => 'spec/fixtures/openstack/network',
:service_class => Fog::Identity::OpenStack::V3
)
@identity_service = openstack_vcr.service
end
it 'CRUD subnets' do
VCR.use_cassette('subnets_crud') do
begin
foonet = @service.networks.create(:name => 'foo-net12', :shared => false)
subnet = @service.subnets.create(
:name => "my-network",
:network_id => foonet.id,
:cidr => '172.16.0.0/16',
:ip_version => 4,
:gateway_ip => nil
)
subnet.name.must_equal 'my-network'
ensure
subnet.destroy if subnet
foonet.destroy if foonet
end
end
end
it 'CRUD rbacs' do
VCR.use_cassette('rbacs_crud') do
begin
own_project = @identity_service.projects.select { |p| p.name == @current_project }.first
other_project = @identity_service.projects.select { |p| p.name != @current_project }.first
foonet = @service.networks.create(:name => 'foo-net23', :tenant_id => own_project.id)
# create share access for other project
rbac = @service.rbac_policies.create(
:object_type => 'network',
:object_id => foonet.id,
:tenant_id => own_project.id,
:target_tenant => other_project.id,
:action => 'access_as_shared'
)
rbac.target_tenant.must_equal other_project.id
foonet.reload.shared.must_equal false
@service.rbac_policies.all(:object_id => foonet.id).length.must_equal 1
# get
@service.rbac_policies.find_by_id(rbac.id).wont_equal nil
# change share target to own project
rbac.target_tenant = own_project.id
rbac.save
foonet.reload.shared.must_equal true
# delete the sharing
rbac.destroy
rbac = nil
@service.rbac_policies.all(:object_id => foonet.id).length.must_equal 0
foonet.reload.shared.must_equal false
ensure
rbac.destroy if rbac
foonet.destroy if foonet
end
end
end
it 'fails at token expiration on auth with token but not with username+password' do
VCR.use_cassette('token_expiration') do
@auth_token = @identity_service.credentials[:openstack_auth_token]
openstack_vcr = OpenStackVCR.new(
:vcr_directory => 'spec/fixtures/openstack/network',
:service_class => Fog::Network::OpenStack,
:project_scoped => true,
:token_auth => true,
:token => @auth_token
)
@service_with_token = openstack_vcr.service
[@service_with_token, @service].each_with_index do |service, index|
@network_token = service.credentials[:openstack_auth_token]
# any network object would do, take sec group - at least we have a default
@before = service.security_groups.all(:limit => 2).first.tenant_id
# invalidate the token, hopefully it is not a palindrome
# NOTE: token_revoke does not work here, because of neutron keystone-middleware cache
service.instance_variable_set("@auth_token", @network_token.reverse)
# with token
if index == 0
err = -> { service.security_groups.all(:limit => 2) }.must_raise Excon::Errors::Unauthorized
err.message.must_match(/Authentication required/)
# with username+password
else
@after = service.security_groups.all(:limit => 2).first.tenant_id
@before.must_equal @after
end
end
end
end
end
| 35.936937 | 102 | 0.634495 |
398660271ca2ba9e018027faf10365b4576db775 | 1,127 | require 'test_helper'
class PostsControllerTest < ActionController::TestCase
setup do
@post = posts(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:posts)
end
test "should get new" do
get :new
assert_response :success
end
test "should create post" do
assert_difference('Post.count') do
post :create, post: { body: @post.body, likes: @post.likes, title: @post.title, visit_count: @post.visit_count }
end
assert_redirected_to post_path(assigns(:post))
end
test "should show post" do
get :show, id: @post
assert_response :success
end
test "should get edit" do
get :edit, id: @post
assert_response :success
end
test "should update post" do
patch :update, id: @post, post: { body: @post.body, likes: @post.likes, title: @post.title, visit_count: @post.visit_count }
assert_redirected_to post_path(assigns(:post))
end
test "should destroy post" do
assert_difference('Post.count', -1) do
delete :destroy, id: @post
end
assert_redirected_to posts_path
end
end
| 22.54 | 128 | 0.682343 |
33724f6734d7411ed9e134c2cbc6fef00099e515 | 522 | module VagrantPlugins
module DockerProvisioner
module Cap
module Debian
module DockerInstall
def self.docker_install(machine)
machine.communicate.tap do |comm|
comm.sudo("apt-get update -qq -y")
comm.sudo("apt-get install -qq -y --force-yes curl")
comm.sudo("apt-get purge -qq -y lxc-docker* || true")
comm.sudo("curl -sSL https://get.docker.com/ | sh")
end
end
end
end
end
end
end
| 27.473684 | 67 | 0.549808 |
3985bee01c2ac90098a04f3e4e0d36e4b25c0f49 | 2,363 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20161223234057) do
create_table "addresses", force: :cascade do |t|
t.string "label"
t.string "street"
t.string "street2"
t.string "street3"
t.string "number"
t.string "care_of"
t.string "city"
t.string "state"
t.string "zip"
t.float "lat"
t.float "lon"
t.string "has_address_type"
t.integer "has_address_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "farm_cats", force: :cascade do |t|
t.string "name"
t.text "description"
t.string "main_image"
t.integer "farm_cat_id"
t.string "slug"
t.string "has_farm_cats_type"
t.integer "has_farm_cats_id"
t.string "master_class"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "gal_images", force: :cascade do |t|
t.integer "gal_id"
t.string "caption"
t.text "description"
t.string "src"
t.integer "order"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "gals", force: :cascade do |t|
t.integer "main_image_id"
t.string "name"
t.string "has_farm_gals_type"
t.integer "has_farm_gals_id"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "objs", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 32.369863 | 86 | 0.669911 |
bfdc9417c895fefee17121f70398c84dbbd842b7 | 1,482 | # frozen_string_literal: true
require_relative "lib/punchfiller/version"
Gem::Specification.new do |spec|
spec.name = "punchfiller"
spec.version = Punchfiller::VERSION
spec.authors = ["Jorge Junior"]
spec.email = ["[email protected]"]
spec.summary = "Write a short summary, because RubyGems requires one."
spec.description = "Write a longer description or delete this line."
spec.homepage = "https://github.com"
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
spec.metadata["allowed_push_host"] = "https://rubygems.org"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com"
spec.metadata["changelog_uri"] = "https://github.com"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
# Uncomment to register a new dependency of your gem
# spec.add_dependency "example-gem", "~> 1.0"
# For more information and examples about making a new gem, checkout our
# guide at: https://bundler.io/guides/creating_gem.html
end
| 39 | 88 | 0.678138 |
b9f6892f6df2b90a330bc39c2ad02f8e6fde644e | 606 | require 'io/console'
require 'colorize'
require 'yaml'
require_relative './util/cursorable'
require_relative './util/display'
require_relative './board/board'
require_relative './board/evaluator'
require_relative './pieces/piece'
require_relative './pieces/sliding_piece'
require_relative './pieces/queen'
require_relative './pieces/bishop'
require_relative './pieces/rook'
require_relative './pieces/stepping_piece'
require_relative './pieces/knight'
require_relative './pieces/king'
require_relative './pieces/pawn'
require_relative './players/human_player'
require_relative './players/computer_player'
| 30.3 | 44 | 0.80363 |
e8622385f7f46fa2b2ea824dedaec71e9e2f263d | 7,850 | RSpec.describe 'FloatingIp API' do
include Spec::Support::SupportsHelper
describe 'GET /api/floating_ips' do
it 'lists all cloud subnets with an appropriate role' do
floating_ip = FactoryBot.create(:floating_ip)
api_basic_authorize collection_action_identifier(:floating_ips, :read, :get)
get(api_floating_ips_url)
expected = {
'count' => 1,
'subcount' => 1,
'name' => 'floating_ips',
'resources' => [
hash_including('href' => api_floating_ip_url(nil, floating_ip))
]
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to include(expected)
end
it 'forbids access to cloud subnets without an appropriate role' do
api_basic_authorize
get(api_floating_ips_url)
expect(response).to have_http_status(:forbidden)
end
end
describe 'GET /api/floating_ips/:id' do
it 'will show a cloud subnet with an appropriate role' do
floating_ip = FactoryBot.create(:floating_ip)
api_basic_authorize action_identifier(:floating_ips, :read, :resource_actions, :get)
get(api_floating_ip_url(nil, floating_ip))
expect(response.parsed_body).to include('href' => api_floating_ip_url(nil, floating_ip))
expect(response).to have_http_status(:ok)
end
it 'forbids access to a cloud tenant without an appropriate role' do
floating_ip = FactoryBot.create(:floating_ip)
api_basic_authorize
get(api_floating_ip_url(nil, floating_ip))
expect(response).to have_http_status(:forbidden)
end
end
describe 'POST /api/floating_ips' do
it 'forbids access to floating ips without an appropriate role' do
api_basic_authorize
post(api_floating_ips_url, :params => gen_request(:query, ""))
expect(response).to have_http_status(:forbidden)
end
it "queues the creating of floating ip" do
api_basic_authorize collection_action_identifier(:floating_ips, :create)
provider = FactoryBot.create(:ems_openstack, :name => 'test_provider')
request = {
"action" => "create",
"resource" => {
"ems_id" => provider.network_manager.id,
"name" => "test_floating_ip"
}
}
post(api_floating_ips_url, :params => request)
expect_multiple_action_result(1, :success => true, :message => /Creating Floating Ip test_floating_ip for Provider #{provider.name}/, :task => true)
end
it "raises error when provider does not support creating of floating ips" do
api_basic_authorize collection_action_identifier(:floating_ips, :create)
provider = FactoryBot.create(:ems_amazon, :name => 'test_provider')
request = {
"action" => "create",
"resource" => {
"ems_id" => provider.network_manager.id,
"name" => "test_floating_ip"
}
}
post(api_floating_ips_url, :params => request)
expect_bad_request(/Create.*not.*supported/)
end
end
describe "POST /api/floating_ips/:id" do
let(:ems) { FactoryBot.create(:ems_openstack) }
let(:tenant) { FactoryBot.create(:cloud_tenant_openstack, :ext_management_system => ems) }
let(:floating_ip) { FactoryBot.create(:floating_ip_openstack, :ext_management_system => ems.network_manager, :cloud_tenant => tenant) }
it "can queue the updating of a floating ip" do
api_basic_authorize(action_identifier(:floating_ips, :edit))
post(api_floating_ip_url(nil, floating_ip), :params => {:action => 'edit', :status => "inactive"})
expected = {
'success' => true,
'message' => a_string_including('Updating Floating Ip'),
'task_href' => a_string_matching(api_tasks_url),
'task_id' => a_kind_of(String)
}
expect(response.parsed_body).to include(expected)
expect(response).to have_http_status(:ok)
end
it "can't queue the updating of a floating ip unless authorized" do
api_basic_authorize
post(api_floating_ip_url(nil, floating_ip), :params => {:action => 'edit', :status => "inactive"})
expect(response).to have_http_status(:forbidden)
end
end
describe "DELETE /api/floating_ips" do
let(:floating_ip) { FactoryBot.create(:floating_ip_openstack) }
it "can delete a floating ip" do
api_basic_authorize(action_identifier(:floating_ips, :delete))
delete(api_floating_ip_url(nil, floating_ip))
expect(response).to have_http_status(:no_content)
end
it "will not delete a floating ip unless authorized" do
api_basic_authorize
delete(api_floating_ip_url(nil, floating_ip))
expect(response).to have_http_status(:forbidden)
end
end
describe "POST /api/floating_ips with delete action" do
it "can delete a floating ip" do
ems = FactoryBot.create(:ems_network)
floating_ip = FactoryBot.create(:floating_ip_openstack, :ext_management_system => ems)
api_basic_authorize(action_identifier(:floating_ips, :delete, :resource_actions))
post(api_floating_ip_url(nil, floating_ip), :params => gen_request(:delete))
expect_single_action_result(:success => true, :task => true, :message => /Deleting Floating Ip/)
end
it "will not delete a floating ip unless authorized" do
floating_ip = FactoryBot.create(:floating_ip)
api_basic_authorize
post(api_floating_ip_url(nil, floating_ip), :params => {:action => "delete"})
expect(response).to have_http_status(:forbidden)
end
it "can delete multiple floating_ips" do
ems = FactoryBot.create(:ems_network)
floating_ip1, floating_ip2 = FactoryBot.create_list(:floating_ip_openstack, 2, :ext_management_system => ems)
api_basic_authorize(action_identifier(:floating_ips, :delete, :resource_actions))
post(api_floating_ips_url, :params => {:action => "delete", :resources => [{:id => floating_ip1.id}, {:id => floating_ip2.id}]})
expect_multiple_action_result(2, :success => true, :task => true, :message => /Deleting Floating Ip/)
end
it "forbids multiple floating ip deletion without an appropriate role" do
floating_ip1, floating_ip2 = FactoryBot.create_list(:floating_ip, 2)
expect_forbidden_request do
post(api_floating_ips_url, :params => {:action => "delete", :resources => [{:id => floating_ip1.id}, {:id => floating_ip2.id}]})
end
end
it "raises an error when delete not supported for floating ip" do
floating_ip = FactoryBot.create(:floating_ip)
api_basic_authorize(action_identifier(:floating_ips, :delete, :resource_actions))
post(api_floating_ip_url(nil, floating_ip), :params => gen_request(:delete))
expect_bad_request(/Delete for Floating Ip/)
end
end
describe 'OPTIONS /api/floating_ips' do
it 'returns a DDF schema for add when available via OPTIONS' do
zone = FactoryBot.create(:zone, :name => "api_zone")
provider = FactoryBot.create(:ems_network, :zone => zone)
stub_supports(provider.class::FloatingIp, :create)
stub_params_for(provider.class::FloatingIp, :create, :fields => [])
options(api_floating_ips_url(:ems_id => provider.id))
expect(response.parsed_body['data']).to match("form_schema" => {"fields" => []})
expect(response).to have_http_status(:ok)
end
end
describe 'OPTIONS /api/floating_ips/:id' do
it 'returns a DDF schema for edit when available via OPTIONS' do
floating_ip = FactoryBot.create(:floating_ip)
stub_supports(floating_ip.class, :update)
stub_params_for(floating_ip.class, :update, :fields => [])
options(api_floating_ip_url(nil, floating_ip))
expect(response).to have_http_status(:ok)
expect(response.parsed_body['data']).to include("form_schema" => {"fields" => []})
end
end
end
| 37.203791 | 154 | 0.685223 |
e9df4677089bff9599f9347f7d59b9688f21847d | 1,550 | module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Remembers a user in a persistent session.
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
# Returns true if the given user is the current user.
def current_user?(user)
user == current_user
end
# Returns the user corresponding to the remember token cookie.
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
@current_user = user
end
end
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Forgets a persistent session.
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
# Logs out the current user.
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
# Redirects to stored location (or to the default).
def redirect_back_or(default)
redirect_to(session[:forwarding_url] || default)
session.delete(:forwarding_url)
end
# Stores the URL trying to be accessed.
def store_location
session[:forwarding_url] = request.original_url if request.get?
end
end
| 24.21875 | 73 | 0.685161 |
e85bec563ce8e7bba7303ba9312b8fdb0e1651c4 | 276 | module HashExt
module Traverse
def self.traverse(hash, &block)
hash.inject({}) do |h,(k,v)|
if Hash === v
v = traverse(v,&block)
end
nk, nv = block.call(k,v)
h[nk] = nv unless nk.nil?
h
end
end
end
end
| 18.4 | 35 | 0.48913 |
6154cb16ddeecd732ff2e04ec94d76de6721e3d5 | 691 | #
# Cookbook Name:: nova
# Recipe:: xen
#
# Copyright 2010, Opscode, Inc.
# Copyright 2011, Dell, 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.
#
node.set[:nova][:libvirt_type] = "xen"
| 31.409091 | 74 | 0.738061 |
081bbc011a5094958d1cda2ce3b7ae83b0bef03c | 704 | # typed: false
require "spec_helper"
describe ParamsCleaner do
describe "#cleaned" do
it "makes an array of a array-like hash" do
params = { "foo" => { "0" => "bar", "1" => "baz" } }
cleaned = ParamsCleaner.new(params).cleaned
expect(cleaned).to eql("foo" => %w(bar baz))
end
it "leaves normal params alone" do
params = { "foo" => "bar" }
cleaned = ParamsCleaner.new(params).cleaned
expect(cleaned).to eql(params)
end
it "does not touch other types of hash-params " do
params = { "foo" => { "from" => "bar", "to" => "baz" } }
cleaned = ParamsCleaner.new(params).cleaned
expect(cleaned).to eql(params)
end
end
end
| 22.709677 | 62 | 0.588068 |
33dc907c4229057c6a9513c5e3c75e034ae959da | 7,880 | require 'open3'
require 'puppet/version'
require 'spec_helper'
require 'tempfile'
RSpec.describe 'exercising a device provider' do
let(:common_args) { '--verbose --trace --strict=error --modulepath spec/fixtures' }
let(:default_type_values) do
'string="meep" boolean=true integer=15 float=1.23 ensure=present variant_pattern=AE321EEF '\
'url="http://www.puppet.com" boolean_param=false integer_param=99 float_param=3.21 '\
'ensure_param=present variant_pattern_param=0xAE321EEF url_param="https://www.google.com"'
end
before(:all) do
if Gem::Version.new(Puppet::PUPPETVERSION) >= Gem::Version.new('5.3.0') && Gem::Version.new(Puppet::PUPPETVERSION) < Gem::Version.new('5.4.0')
# work around https://tickets.puppetlabs.com/browse/PUP-8632 and https://tickets.puppetlabs.com/browse/PUP-9047
FileUtils.mkdir_p(File.expand_path('~/.puppetlabs/opt/puppet/cache/devices/the_node/state'))
end
end
describe 'using `puppet resource`' do
it 'manages resources on the target system' do
stdout_str, status = Open3.capture2e("puppet resource #{common_args} device_provider foo ensure=present #{default_type_values}")
expect(stdout_str).to match %r{Notice: /Device_provider\[foo\]/ensure: defined 'ensure' as 'present'}
expect(status).to eq 0
end
context 'with strict checking at error level' do
let(:common_args) { '--verbose --trace --strict=error --modulepath spec/fixtures' }
it 'deals with canonicalized resources correctly' do
stdout_str, status = Open3.capture2e("puppet resource #{common_args} device_provider wibble ensure=present #{default_type_values}")
stdmatch = 'Error: /Device_provider\[wibble\]: Could not evaluate: device_provider\[wibble\]#get has not provided canonicalized values.\n'\
'Returned values: \{:name=>"wibble", :ensure=>"present", :string=>"sample", :string_ro=>"fixed"\}\n'\
'Canonicalized values: \{:name=>"wibble", :ensure=>"present", :string=>"changed", :string_ro=>"fixed"\}'
expect(stdout_str).to match %r{#{stdmatch}}
expect(status).to be_success
end
end
context 'with strict checking at warning level' do
let(:common_args) { '--verbose --trace --strict=warning --modulepath spec/fixtures' }
it 'deals with canonicalized resources correctly' do
stdout_str, status = Open3.capture2e("puppet resource #{common_args} device_provider wibble ensure=present #{default_type_values}")
stdmatch = 'Warning: device_provider\[wibble\]#get has not provided canonicalized values.\n'\
'Returned values: \{:name=>"wibble", :ensure=>"present", :string=>"sample", :string_ro=>"fixed"\}\n'\
'Canonicalized values: \{:name=>"wibble", :ensure=>"present", :string=>"changed", :string_ro=>"fixed"\}'
expect(stdout_str).to match %r{#{stdmatch}}
expect(status).to be_success
end
end
context 'with strict checking turned off' do
let(:common_args) { '--verbose --trace --strict=off --modulepath spec/fixtures' }
it 'reads resources from the target system' do
stdout_str, status = Open3.capture2e("puppet resource #{common_args} device_provider")
expected_values = 'device_provider { \'wibble\': \n\s+ensure => \'present\',\n\s+string => \'sample\',\n\#\s+string_ro => \'fixed\', # Read Only\n string_param => \'default value\',\n}'
fiddle_deprecate_msg = "DL is deprecated, please use Fiddle\n"
win32_deprecate_msg = ".*Struct layout is already defined for class Windows::ServiceStructs::SERVICE_STATUS_PROCESS.*\n"
expect(stdout_str.strip).to match %r{\A(#{fiddle_deprecate_msg}|#{win32_deprecate_msg})?#{expected_values}\Z}
expect(status).to eq 0
end
it 'outputs resources as yaml' do
stdout_str, status = Open3.capture2e("puppet resource #{common_args} device_provider --to_yaml")
expected_values = 'device_provider: |2\n\s+wibble:\n\s+ensure: :present\n\s+string: sample\n\s+string_ro: fixed\n\s+string_param: default value'
fiddle_deprecate_msg = "DL is deprecated, please use Fiddle\n"
win32_deprecate_msg = ".*Struct layout is already defined for class Windows::ServiceStructs::SERVICE_STATUS_PROCESS.*\n"
expect(stdout_str.strip).to match %r{\A(#{fiddle_deprecate_msg}|#{win32_deprecate_msg})?#{expected_values}\Z}
expect(status).to eq 0
end
it 'deals with canonicalized resources correctly' do
stdout_str, status = Open3.capture2e("puppet resource #{common_args} device_provider wibble ensure=present #{default_type_values}")
stdmatch = 'Notice: /Device_provider\[wibble\]/string: string changed \'sample\' to \'changed\''
expect(stdout_str).to match %r{#{stdmatch}}
expect(status).to be_success
end
end
end
describe 'using `puppet device`' do
let(:common_args) { super() + ' --target the_node' }
let(:device_conf) { Tempfile.new('device.conf') }
let(:device_conf_content) do
<<DEVICE_CONF
[the_node]
type test_device
url file://#{device_credentials.path}
DEVICE_CONF
end
let(:device_credentials) { Tempfile.new('credentials.txt') }
let(:device_credentials_content) do
<<DEVICE_CREDS
{
username: foo
secret: wibble
}
DEVICE_CREDS
end
def is_device_apply_supported?
Gem::Version.new(Puppet::PUPPETVERSION) >= Gem::Version.new('5.3.6') && Gem::Version.new(Puppet::PUPPETVERSION) != Gem::Version.new('5.4.0')
end
before(:each) do
skip "No device --apply in puppet before v5.3.6 nor in v5.4.0 (v#{Puppet::PUPPETVERSION} is installed)" unless is_device_apply_supported?
device_conf.write(device_conf_content)
device_conf.close
device_credentials.write(device_credentials_content)
device_credentials.close
end
after(:each) do
device_conf.unlink
device_credentials.unlink
end
context 'with no config specified' do
it 'errors out' do
stdout_str, _status = Open3.capture2e("puppet device #{common_args}")
expect(stdout_str).to match %r{Target device / certificate.*not found}
end
end
it 'applies a catalog successfully' do
Tempfile.create('apply_success') do |f|
f.write 'notify { "foo": }'
f.close
stdout_str, _status = Open3.capture2e("puppet device #{common_args} --deviceconfig #{device_conf.path} --apply #{f.path}")
expect(stdout_str).to match %r{Compiled catalog for the_node}
expect(stdout_str).to match %r{defined 'message' as 'foo'}
expect(stdout_str).not_to match %r{Error:}
end
end
it 'has the "foo" fact set to "bar"' do
Tempfile.create('fact_set') do |f|
f.write 'if $facts["foo"] != "bar" { fail("fact not found") }'
f.close
stdout_str, status = Open3.capture2e("puppet device #{common_args} --deviceconfig #{device_conf.path} --apply #{f.path}")
expect(stdout_str).not_to match %r{Error:}
expect(status).to eq 0
end
end
context 'with a device resource in the catalog' do
it 'applies the catalog successfully' do
Tempfile.create('fact_set') do |f|
f.write 'device_provider{ "foo":' \
'ensure => "present", boolean => true, integer => 15, float => 1.23, variant_pattern => "0x1234ABCD", '\
'url => "http://www.google.com", boolean_param => false, integer_param => 99, float_param => 3.21, '\
'ensure_param => "present", variant_pattern_param => "9A2222ED", url_param => "http://www.puppet.com" }'
f.close
stdout_str, _status = Open3.capture2e("puppet device #{common_args} --deviceconfig #{device_conf.path} --apply #{f.path}")
expect(stdout_str).not_to match %r{Error:}
end
end
end
end
end
| 46.904762 | 194 | 0.668909 |
e2b2084924ec14246056ae4000dfa323065db167 | 1,466 | require 'travis/build/git/clone'
require 'travis/build/git/ssh_key'
require 'travis/build/git/submodules'
require 'travis/build/git/tarball'
module Travis
module Build
class Git
DEFAULTS = {
git: { depth: 50, submodules: true, strategy: 'clone' }
}
attr_reader :sh, :data
def initialize(sh, data)
@sh = sh
@data = data
end
def checkout
disable_interactive_auth
install_ssh_key
if use_tarball?
download_tarball
else
clone_or_fetch
submodules
end
rm_key
end
private
def disable_interactive_auth
sh.export 'GIT_ASKPASS', 'echo', :echo => false
end
def install_ssh_key
SshKey.new(sh, data).apply if data.ssh_key
end
def download_tarball
Tarball.new(sh, data).apply
end
def clone_or_fetch
Clone.new(sh, data).apply
end
def submodules
Submodules.new(sh, data).apply if submodules?
end
def rm_key
sh.rm '~/.ssh/source_rsa', force: true, echo: false
end
def config
DEFAULTS.merge(data.config)
end
def submodules?
config[:git][:submodules]
end
def use_tarball?
config[:git][:strategy] == 'tarball'
end
def dir
data.slug
end
end
end
end
| 18.794872 | 63 | 0.545703 |
ffe6fcdc53c89c1ebd2bc3352ee3a6b00262ff12 | 2,567 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Redis::Mgmt::V2018_03_01
module Models
#
# The resource model definition for a ARM tracked top level resource
#
class TrackedResource < Resource
include MsRestAzure
# @return [Hash{String => String}] Resource tags.
attr_accessor :tags
# @return [String] The geo-location where the resource lives
attr_accessor :location
#
# Mapper for TrackedResource class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'TrackedResource',
type: {
name: 'Composite',
class_name: 'TrackedResource',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
location: {
client_side_validation: true,
required: true,
serialized_name: 'location',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 27.902174 | 72 | 0.439813 |
91f6bad4d1a9a2a345d90d4c21baf89c04aa8a09 | 750 | module Spree
class SolidusVariantOptionsSettings < Spree::Preferences::Configuration
preference :allow_select_outofstock, :boolean, :default => false
preference :default_instock, :boolean, :default => false
preference :main_option_type_id, :integer, :default => 1
preference :main_option_type_label, :string, :default => 'color'
preference :option_value_url, :string, :default => '/spree/option_values/:id/:style/:basename.:extension'
preference :option_value_path, :string, :default => '/spree/option_values/:id/:style/:basename.:extension'
preference :option_value_styles, :string, default: "{\"mini\":\"32x32#\",\"normal\":\"128x128>#\"}"
preference :option_value_default_style, :string, default: 'mini'
end
end | 62.5 | 110 | 0.733333 |
91714aa54904f58ed6012aec7bc9dacd5259eef3 | 236 | class AddNameToUser < ActiveRecord::Migration[5.2]
def change
add_column :users, :first_name, :string
add_column :users, :last_name, :string
add_column :users, :class, :integer
add_column :users, :bio, :text
end
end
| 26.222222 | 50 | 0.70339 |
f70d6dc5dd2ca5c906ab30d79ff30dd1f68445fe | 1,150 | require "stub_constant/version"
class StubConstant
def self.module(full_name)
new(full_name).stub_with { Module.new }
end
def self.klass(full_name)
new(full_name).stub_with { Class.new }
end
def self.value(full_name, value)
new(full_name).stub_with { value }
end
def initialize(full_name)
@full_name = full_name
end
def stub_with
full_name.to_s.split(/::/).inject(Object) do |context, name|
begin
context.const_get(name)
rescue NameError
# Defer substitution of a stub module/class to the last possible
# moment by overloading const_missing. We use a module here so
# we can "stack" const_missing definitions for various
# constants.
mod = Module.new do
define_method(:const_missing) do |missing_const_name|
if missing_const_name.to_s == name.to_s
value = yield
const_set(name, value)
value
else
super(missing_const_name)
end
end
end
context.extend(mod)
end
end
end
private
attr_reader :full_name
end
| 23.469388 | 72 | 0.622609 |
f753d76bd2283f768fd5d5e9a8af95abae8fae1a | 834 | asterisk_user = node['asterisk']['user']
asterisk_group = node['asterisk']['group']
user asterisk_user do
system true
end
group asterisk_group do
system true
end
include_recipe "asterisk::#{node['asterisk']['install_method']}"
service "asterisk" do
supports :restart => true, :reload => true, :status => :true, :debug => :true,
"logger-reload" => true, "extensions-reload" => true,
"restart-convenient" => true, "force-reload" => true
action :enable
end
%w(lib/asterisk spool/asterisk run/asterisk log/asterisk).each do |subdir|
path = "#{node['asterisk']['prefix']['state']}/#{subdir}"
directory path do
recursive true
end
execute "#{path} ownership" do
command "chown -Rf #{asterisk_user}:#{asterisk_group} #{path}"
end
end
include_recipe 'asterisk::config'
include_recipe 'asterisk::init'
| 23.828571 | 80 | 0.690647 |
1d28b846618c0ae349b3df872ca5c21602aeca86 | 1,984 | #!/usr/bin/env ruby
require 'rubygems'
require 'activesupport'
require 'actionmailer'
RAILS_ROOT = File.expand_path(File.dirname(__FILE__) + '/..')
class Commit
def self.parse(full_log)
full_log.split(/^commit /).map do |log|
log.blank? ? nil : new("commit #{log}")
end.compact
end
attr_reader :id, :author, :date, :files
def initialize(log)
lines = log.split("\n")
@message = []
@files = []
while !lines.empty?
line = lines.shift
if line.blank?
# skip
elsif line =~ /^commit (\w+)$/
@id = $1
elsif line =~ /^Author\: ([\w ]+)/
@author = $1
elsif line =~ /^Date\: +([\d-]+)/
@date = Date.strptime($1)
elsif line =~ /^ {4}(.+)$/
@message << line.strip
elsif line =~ /^ (.+?) \| /
@files << $1.strip
end
end
end
def message(join_with = ' / ')
@message.join(join_with)
end
def short_id
id.first(6)
end
def file_info
if files.size > 6
["#{files.size} files affected"]
else
files
end.map do |line|
format "* #{line}", 4
end.join
end
def summary
text = "#{message} [#{short_id}]"
format(text)
end
protected
def format(text, indent = 2)
Text::Format.new( :columns => 72, :first_indent => indent, :body_indent => indent, :text => text ).format
end
end
full_log = `git log --summary --stat --no-merges --date=short -- #{RAILS_ROOT}`
commit_map = Commit.parse(full_log).inject(ActiveSupport::OrderedHash.new) do |result, commit|
result[commit.date] ||= ActiveSupport::OrderedHash.new
result[commit.date][commit.author] ||= []
result[commit.date][commit.author] << commit
result
end
commit_map.each do |date, details|
details.each do |author, commits|
puts "(#{date}) #{author}"
commits.each do |commit|
puts "\n" + commit.summary + commit.file_info
end
puts "\n"
end
end
| 21.106383 | 117 | 0.565524 |
d565ab1a0a02cfe54750bcb2a6fdfa9d7cc4cb77 | 77 | json.partial! 'users/user', user: @user
# Example:
# { "username": "mike" } | 19.25 | 39 | 0.61039 |
e9b7633bc6e70d7f25816f394af4422ee0cfa1ba | 425 | class AddReleaseInfosToMedium < ActiveRecord::Migration[6.0]
def up
add_column :media, :released_at, :datetime
add_column :media, :release_date, :datetime
Medium.where(released: ['all', 'users', 'subscribers']).each do |m|
m.update_columns(released_at: m.created_at)
end
end
def down
remove_column :media, :released_at, :datetime
remove_column :media, :release_date, :datetime
end
end
| 26.5625 | 71 | 0.708235 |
5dc89717f36fb07bb983bd3b9a6bc21410474934 | 411 | module Ebanx
module Command
class Direct < Command
def initialize(params)
@params = params
@request_method = :post
@request_action = 'direct'
@response_type = :json
@request_body = true
end
def validate
validate_presence :operation
validate_presence :mode
validate_presence :payment
end
end
end
end
| 20.55 | 36 | 0.586375 |
33ef2c93b656a2680838d7468e2f306ba6811f11 | 8,292 | module MoSQL
class Streamer
include MoSQL::Logging
BATCH = 1000
attr_reader :options, :tailer
NEW_KEYS = [:options, :tailer, :mongo, :sql, :schema]
def initialize(opts)
NEW_KEYS.each do |parm|
unless opts.key?(parm)
raise ArgumentError.new("Required argument `#{parm}' not provided to #{self.class.name}#new.")
end
instance_variable_set(:"@#{parm.to_s}", opts[parm])
end
@done = false
end
def stop
@done = true
end
def import
if options[:reimport] || tailer.read_position.nil?
initial_import
end
if options[:empty_table_import]
import_data_for_empty_tables
end
end
def collection_for_ns(ns)
dbname, collection = ns.split(".", 2)
@mongo.db(dbname).collection(collection)
end
def unsafe_handle_exceptions(ns, obj)
begin
yield
rescue Sequel::DatabaseError => e
wrapped = e.wrapped_exception
if wrapped.result && options[:unsafe]
log.warn("Ignoring row (#{obj.inspect}): #{e}")
else
log.error("Error processing #{obj.inspect} for #{ns}.")
raise e
end
end
end
def bulk_upsert(table, ns, items)
begin
@schema.copy_data(table.db, ns, items)
rescue Sequel::DatabaseError => e
log.debug("Bulk insert error (#{e}), attempting invidual upserts...")
cols = @schema.all_columns(@schema.find_ns(ns))
items.each do |it|
h = {}
cols.zip(it).each { |k,v| h[k] = v }
unsafe_handle_exceptions(ns, h) do
@sql.upsert!(table, @schema.primary_sql_key_for_ns(ns), h)
end
end
end
end
def with_retries(tries=10)
tries.times do |try|
begin
yield
rescue Mongo::ConnectionError, Mongo::ConnectionFailure, Mongo::OperationFailure => e
# Duplicate key error
raise if e.kind_of?(Mongo::OperationFailure) && [11000, 11001].include?(e.error_code)
# Cursor timeout
raise if e.kind_of?(Mongo::OperationFailure) && e.message =~ /^Query response returned CURSOR_NOT_FOUND/
delay = 0.5 * (1.5 ** try)
log.warn("Mongo exception: #{e}, sleeping #{delay}s...")
sleep(delay)
end
end
end
def track_time
start = Time.now
yield
Time.now - start
end
def import_data_for_empty_tables
new_collections = @schema.find_empty_tables(@sql.db)
import_data_for_collections(new_collections)
end
def import_data_for_collections(importcollections)
importcollections.each do | mongodb, collections |
collections.each do | collection |
collection.each do | collectionname, spec |
ns = "#{mongodb}.#{collectionname}"
db = @mongo.db(mongodb)
collections = db.collections.select { |c| {collectionname => spec}.key?(c.name) }
collections.each do | collection|
import_collection(ns, collection,{})
end
end
end
end
end
def initial_import
@schema.create_schema(@sql.db, !options[:no_drop_tables])
unless options[:skip_tail]
start_state = {
'time' => nil,
'position' => @tailer.most_recent_position
}
end
dbnames = []
if options[:dbname]
log.info "Skipping DB scan and using db: #{options[:dbname]}"
dbnames = [ options[:dbname] ]
else
dbnames = @mongo.database_names
end
dbnames.each do |dbname|
spec = @schema.find_db(dbname)
if(spec.nil?)
log.info("Mongd DB '#{dbname}' not found in config file. Skipping.")
next
end
log.info("Importing for Mongo DB #{dbname}...")
db = @mongo.db(dbname)
collections = db.collections.select { |c| spec.key?(c.name) }
collections.each do |collection|
ns = "#{dbname}.#{collection.name}"
import_collection(ns, collection, spec[collection.name][:meta][:filter])
exit(0) if @done
end
end
tailer.save_state(start_state) unless options[:skip_tail]
end
def did_truncate; @did_truncate ||= {}; end
def import_collection(ns, collection, filter)
log.info("Importing for #{ns}...")
count = 0
batch = []
table = @sql.table_for_ns(ns)
unless options[:no_drop_tables] || did_truncate[table.first_source]
table.truncate
did_truncate[table.first_source] = true
end
start = Time.now
sql_time = 0
collection.find(filter, {:batch_size => BATCH, :timeout => false} ) do |cursor|
with_retries do
cursor.each do |obj|
batch << @schema.transform(ns, obj)
count += 1
if batch.length >= BATCH
sql_time += track_time do
bulk_upsert(table, ns, batch)
end
elapsed = Time.now - start
log.info("Imported #{count} rows (#{elapsed}s, #{sql_time}s SQL)...")
batch.clear
exit(0) if @done
end
end
end
end
unless batch.empty?
bulk_upsert(table, ns, batch)
end
end
def optail
tail_from = options[:tail_from]
if tail_from.is_a? Time
tail_from = tailer.most_recent_position(tail_from)
end
tailer.tail(:from => tail_from, :filter => options[:oplog_filter])
until @done
tailer.stream(1000) do |op|
handle_op(op)
end
end
end
def sync_object(ns, selector)
obj = collection_for_ns(ns).find_one(selector)
if obj
unsafe_handle_exceptions(ns, obj) do
@sql.upsert_ns(ns, obj)
end
else
@sql.delete_ns(ns, selector)
end
end
def handle_op(op)
log.debug("processing op: #{op.inspect}")
unless op['ns'] && op['op']
log.warn("Weird op: #{op.inspect}")
return
end
# First, check if this was an operation performed via applyOps. If so, call handle_op with
# for each op that was applied.
# The oplog format of applyOps commands can be viewed here:
# https://groups.google.com/forum/#!topic/mongodb-user/dTf5VEJJWvY
if op['op'] == 'c' && (ops = op['o']['applyOps'])
ops.each { |op| handle_op(op) }
return
end
unless @schema.find_ns(op['ns'])
log.debug("Skipping op for unknown ns #{op['ns']}...")
return
end
ns = op['ns']
dbname, collection_name = ns.split(".", 2)
case op['op']
when 'n'
log.debug("Skipping no-op #{op.inspect}")
when 'i'
if collection_name == 'system.indexes'
log.info("Skipping index update: #{op.inspect}")
else
unsafe_handle_exceptions(ns, op['o']) do
@sql.upsert_ns(ns, op['o'])
end
end
when 'u'
selector = op['o2']
update = op['o']
if update.keys.any? { |k| k.start_with? '$' }
log.debug("resync #{ns}: #{selector['_id']} (update was: #{update.inspect})")
sync_object(ns, selector)
else
# The update operation replaces the existing object, but
# preserves its _id field, so grab the _id off of the
# 'query' field -- it's not guaranteed to be present on the
# update.
primary_sql_keys = @schema.primary_sql_key_for_ns(ns)
schema = @schema.find_ns!(ns)
keys = {}
primary_sql_keys.each do |key|
source = schema[:columns].find {|c| c[:name] == key }[:source]
keys[source] = selector[source]
end
log.debug("upsert #{ns}: #{keys}")
update = keys.merge(update)
unsafe_handle_exceptions(ns, update) do
@sql.upsert_ns(ns, update)
end
end
when 'd'
if options[:ignore_delete]
log.debug("Ignoring delete op on #{ns} as instructed.")
else
@sql.delete_ns(ns, op['o'])
end
else
log.info("Skipping unknown op #{op.inspect}")
end
end
end
end
| 28.494845 | 114 | 0.561867 |
6a4674ad150c1fac7dd27e1561858a5d5af68346 | 483 | # frozen_string_literal: true
module AwsSdkCodeGenerator
module Views
module Features
class StepDefinitions < View
# @param [Hash] options
# @option options [required, Service] :service
def initialize(options)
service = options.fetch(:service)
@var_name = service.identifier
@module_name = service.module_name
end
attr_reader :var_name
attr_reader :module_name
end
end
end
end
| 21 | 54 | 0.63354 |
5d18aabffb35f0a300cb82515162023dc58f7223 | 1,195 | module Spree
module ProductsHelper
def product_bullet_point(product)
#product.bullet_point.to_s.tr("\n","|").split('|').map{|x| tag_li(x) }.join
content_tag :ul, class: '' do
result = product.bullet_point.to_s.tr("\n","|").split('|').map do |point|
css_class = ""
unless point.empty?
content_tag :li, class: css_class do
point
end
end
end
safe_join(result, "\n")
end
end
def product_description(product)
description = if Spree::Config[:show_raw_product_description]
product.description
else
str=product.description.to_s.gsub(/(<br>?)/m,'<p></p>')
str.to_s.gsub(/(.*?)\r?\n\r?\n/m, '<p>\1</p>')
# product.description.to_s.gsub(/(.*?)\r?\n\r?\n/m, '<p>\1</p>')
end
description.blank? ? Spree.t(:product_has_no_description) : description
end
private
def tag_li(str)
li = content_tag :li do
str
end
li
end
end
end
| 25.425532 | 85 | 0.478661 |
6a1c5b2169abb21991c63247fcbfa233e060a1bf | 3,199 | require File.join(File.dirname(__FILE__), '../test_helper')
class SessionsControllerTest < ActionController::TestCase
def setup
login_as(:nari)
SessionsController.class_eval do
def authenticate(identity_url = "")
after_autenticate(true, params[:openid_url], "OK", "nickname" => "hoge")
end
end
end
test "shuold get index" do
get :index
assert_not_nil assigns(:user)
end
test "shuold create" do
@request.session[:user_id] = nil
post :create, :user => users(:nari).id, :openid_url => users(:nari).openid_url
assert_not_nil @request.session[:user_id]
assert_not_nil assigns(:user)
assert_redirected_to :controller => "reminders", :user => users(:nari).login, :action => :today
end
test "shuold create to update" do
@request.session[:user_id] = nil
post :create, :user => users(:nari).id, :openid_url => "update_url"
assert_not_nil @request.session[:user_id]
assert_not_nil assigns(:user)
assert_redirected_to "/#{assigns(:user).login}/sessions/edit"
end
test "shuold create fail" do
@request.session[:user_id] = nil
post :create, :user => users(:nari).id
assert_redirected_to sessions_path
end
test "shuold create fail with exception" do
SessionsController.class_eval do
def authenticate(identity_url = "")
raise ActiveRecord::RecordNotSaved, "Error"
end
end
@request.session[:user_id] = nil
post :create, :user => users(:nari).id, :openid_url => users(:nari).openid_url
assert_not_nil flash[:notice]
assert_redirected_to :action => "index"
end
test "shuold get edit" do
get :edit, :user => users(:nari).login
assert_not_nil assigns(:user)
end
test "shuold update" do
get :update, :user => users(:nari).login, :edit_user => {:login => "update"}
assert_equal "update", assigns(:user).login
end
test "shuold update fail" do
get :update, :user => users(:nari).login, :edit_user => {:login => "aaron"}
assert_template "edit"
assert_equal "aaron", assigns(:user).login
assert_not_equal "aaron", @controller.instance_eval("@current_user.login")
end
test "shuold destroy" do
delete :destroy, :user => users(:nari).login
assert_nil session[:user_id]
assert_redirected_to "/login"
end
test "should_login_with_cookie" do
get :create, :openid_url => users(:nari).openid_url
assert_not_nil cookies["brushup_auth_token"]
# cookie copy
users(:nari).remember_token = cookies["brushup_auth_token"][0]
@request.cookies["brushup_auth_token"] = cookie_for(:nari)
# session clear
@request.session[:user_id] = nil
@controller.instance_eval("@current_user = nil")
get :index
assert @controller.send(:logged_in?)
end
protected
def create_user(options = {})
post :signup, :user => { :login => 'quire', :email => '[email protected]',
:password => 'quire', :password_confirmation => 'quire' }.merge(options)
end
def auth_token(token)
CGI::Cookie.new('name' => 'brushup_auth_token', 'value' => token)
end
def cookie_for(user)
auth_token users(user).remember_token
end
end
| 30.179245 | 99 | 0.667396 |
1c6fb011012bb422b476599039db9078a035afa5 | 854 | # frozen_string_literal: true
module Gitlab
module Graphql
class Variables
Invalid = Class.new(Gitlab::Graphql::StandardGraphqlError)
def initialize(param)
@param = param
end
def to_h
ensure_hash(@param)
end
private
# Handle form data, JSON body, or a blank value
def ensure_hash(ambiguous_param)
case ambiguous_param
when String
if ambiguous_param.present?
ensure_hash(Gitlab::Json.parse(ambiguous_param))
else
{}
end
when Hash, ActionController::Parameters
ambiguous_param
when nil
{}
else
raise Invalid, "Unexpected parameter: #{ambiguous_param}"
end
rescue JSON::ParserError => e
raise Invalid.new(e)
end
end
end
end
| 21.35 | 67 | 0.58548 |
d5f3d02911415c20da6694c778ac44f0c057e379 | 3,207 | require 'spec_helper'
require 'scrape_driver'
require 'reading_scraper'
describe ReadingScraper do
before do
skip "unused"
end
let(:twine) { create(:twine) }
describe "#get_reading" do
let(:scraper) { double('scraper') }
let(:twine_login_url) { "https://twine.cc/login?next=%2F" }
let(:temperature) { 50 }
let(:outside_temperature) { 45 }
let(:html) { "<div class='temperature-value'>#{temperature}</div>" }
let(:reading) { double('reading') }
subject { ReadingScraper.new(twine) }
before do
allow(ScrapeDriver).to receive(:new).and_return scraper
allow(scraper).to receive(:visit).with(twine_login_url)
allow(scraper).to receive(:fill_in).with("email", { with: twine.email})
allow(scraper).to receive(:fill_in).with("password", { with: "33west26"})
allow(scraper).to receive(:click_button).with("signin")
allow(scraper).to receive(:html).and_return html
driver = double('driver')
allow(scraper).to receive(:driver).and_return driver
allow(driver).to receive(:quit)
allow(WeatherMan).to receive(:current_outdoor_temp).
with(twine.user.zip_code).
and_return(outside_temperature)
allow(Reading).to receive(:new_from_twine).
with(temperature, outside_temperature, twine, twine.user).
and_return reading
allow(reading).to receive(:save)
allow(subject).to receive(:sleep)
end
it "instantiates a new driver" do
expect(ScrapeDriver).to receive(:new).and_return scraper
subject.get_reading
end
it "logs into twine.cc" do
expect(scraper).to receive(:visit).with(twine_login_url)
expect(scraper).to receive(:fill_in).with("email", { with: twine.email})
expect(scraper).to receive(:fill_in).with("password", { with: "33west26"})
expect(scraper).to receive(:click_button).with("signin")
subject.get_reading
end
it "fetches outside temperature" do
expect(WeatherMan).to receive(:current_outdoor_temp).
with(twine.user.zip_code).
and_return(outside_temperature)
subject.get_reading
end
it "creates a reading with scraped temperature, fetched outside temperature and twine user" do
expect(Reading).to receive(:new_from_twine).
with(temperature, outside_temperature, twine, twine.user).
and_return reading
expect(reading).to receive(:save)
subject.get_reading
end
it "returns the reading" do
expect(subject.get_reading).to eql reading
end
context "no reading" do
let(:html) { "<div class='temperature-value'></div>" }
it "creates a reading with nil temperature" do
expect(Reading).to receive(:new_from_twine).
with(nil, outside_temperature, twine, twine.user).
and_return reading
expect(reading).to receive(:save)
subject.get_reading
end
end
end
end
| 36.443182 | 98 | 0.611475 |
4a7f73b65151f2dd3cb45ad7c94553520daf9beb | 11,582 | #see the URL below for information on how to write OpenStudio measures
# http://nrel.github.io/OpenStudio-user-documentation/measures/measure_writing_guide/
#see the URL below for information on using life cycle cost objects in OpenStudio
# http://nrel.github.io/OpenStudio-user-documentation/next_steps/life_cycle_costing_examples/
#see the URL below for access to C++ documentation on model objects (click on "model" in the main window to view model objects)
# https://s3.amazonaws.com/openstudio-sdk-documentation/cpp/OpenStudio-1.5.0-doc/model/html/classes.html
#start the measure
class ReduceVentilationByPercentage < OpenStudio::Ruleset::ModelUserScript
#define the name that a user will see, this method may be deprecated as
#the display name in PAT comes from the name field in measure.xml
def name
return "ReduceVentilationByPercentage"
end
#define the arguments that the user will input
def arguments(model)
args = OpenStudio::Ruleset::OSArgumentVector.new
#make a choice argument for model objects
space_type_handles = OpenStudio::StringVector.new
space_type_display_names = OpenStudio::StringVector.new
#putting model object and names into hash
space_type_args = model.getSpaceTypes
space_type_args_hash = {}
space_type_args.each do |space_type_arg|
space_type_args_hash[space_type_arg.name.to_s] = space_type_arg
end
#looping through sorted hash of model objects
space_type_args_hash.sort.map do |key,value|
#only include if space type is used in the model
if value.spaces.size > 0
space_type_handles << value.handle.to_s
space_type_display_names << key
end
end
#add building to string vector with space type
building = model.getBuilding
space_type_handles << building.handle.to_s
space_type_display_names << "*Entire Building*"
#make a choice argument for space type
space_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument("space_type", space_type_handles, space_type_display_names)
space_type.setDisplayName("Apply the Measure to a Specific Space Type or to the Entire Model.")
space_type.setDefaultValue("*Entire Building*") #if no space type is chosen this will run on the entire building
args << space_type
#make an argument for reduction percentage
design_spec_outdoor_air_reduction_percent = OpenStudio::Ruleset::OSArgument::makeDoubleArgument("design_spec_outdoor_air_reduction_percent",true)
design_spec_outdoor_air_reduction_percent.setDisplayName("Design Specification Outdoor Air Reduction (%).")
design_spec_outdoor_air_reduction_percent.setDefaultValue(30.0)
args << design_spec_outdoor_air_reduction_percent
#no cost required to reduce required amount of outdoor air. Cost increase or decrease will relate to system sizing and ongoing energy use due to change in outdoor air provided.
return args
end #end the arguments method
#define what happens when the measure is run
def run(model, runner, user_arguments)
super(model, runner, user_arguments)
#use the built-in error checking
if not runner.validateUserArguments(arguments(model), user_arguments)
return false
end
#assign the user inputs to variables
object = runner.getOptionalWorkspaceObjectChoiceValue("space_type",user_arguments,model)
design_spec_outdoor_air_reduction_percent = runner.getDoubleArgumentValue("design_spec_outdoor_air_reduction_percent",user_arguments)
#check the space_type for reasonableness and see if measure should run on space type or on the entire building
apply_to_building = false
space_type = nil
if object.empty?
handle = runner.getStringArgumentValue("space_type",user_arguments)
if handle.empty?
runner.registerError("No space type was chosen.")
else
runner.registerError("The selected space type with handle '#{handle}' was not found in the model. It may have been removed by another measure.")
end
return false
else
if not object.get.to_SpaceType.empty?
space_type = object.get.to_SpaceType.get
elsif not object.get.to_Building.empty?
apply_to_building = true
else
runner.registerError("Script Error - argument not showing up as space type or building.")
return false
end
end
#check the design_spec_outdoor_air_reduction_percent and for reasonableness
if design_spec_outdoor_air_reduction_percent > 100
runner.registerError("Please enter a value less than or equal to 100 for the Outdoor Air Requirement reduction percentage.")
return false
elsif design_spec_outdoor_air_reduction_percent == 0
runner.registerInfo("No Outdoor Air Requirement adjustment requested, but some life cycle costs may still be affected.")
elsif design_spec_outdoor_air_reduction_percent < 1 and design_spec_outdoor_air_reduction_percent > -1
runner.registerWarning("A Outdoor Air Requirement reduction percentage of #{design_spec_outdoor_air_reduction_percent} percent is abnormally low.")
elsif design_spec_outdoor_air_reduction_percent > 90
runner.registerWarning("A Outdoor Air Requirement reduction percentage of #{design_spec_outdoor_air_reduction_percent} percent is abnormally high.")
elsif design_spec_outdoor_air_reduction_percent < 0
runner.registerInfo("The requested value for Outdoor Air Requirement reduction percentage was negative. This will result in an increase in the Outdoor Air Requirement.")
end
#helper to make numbers pretty (converts 4125001.25641 to 4,125,001.26 or 4,125,001). The definition be called through this measure.
def neat_numbers(number, roundto = 2) #round to 0 or 2)
if roundto == 2
number = sprintf "%.2f", number
else
number = number.round
end
#regex to add commas
number.to_s.reverse.gsub(%r{([0-9]{3}(?=([0-9])))}, "\\1,").reverse
end #end def neat_numbers
#get space design_spec_outdoor_air_objects objects used in the model
design_spec_outdoor_air_objects = model.getDesignSpecificationOutdoorAirs
#todo - it would be nice to give ranges for different calculation methods but would take some work.
#counters needed for measure
altered_instances = 0
#reporting initial condition of model
if design_spec_outdoor_air_objects.size > 0
runner.registerInitialCondition("The initial model contained #{design_spec_outdoor_air_objects.size} design specification outdoor air objects.")
else
runner.registerInitialCondition("The initial model did not contain any design specification outdoor air.")
end
#get space types in model
building = model.building.get
if apply_to_building
space_types = model.getSpaceTypes
affected_area_si = building.floorArea
else
space_types = []
space_types << space_type #only run on a single space type
affected_area_si = space_type.floorArea
end
#split apart any shared uses of design specification outdoor air
design_spec_outdoor_air_objects.each do |design_spec_outdoor_air_object|
direct_use_count = design_spec_outdoor_air_object.directUseCount
next if not direct_use_count > 1
direct_uses = design_spec_outdoor_air_object.sources
original_cloned = false
#adjust count test for direct uses that are component data
direct_uses.each do |direct_use|
component_data_source = direct_use.to_ComponentData
if not component_data_source.empty?
direct_use_count = direct_use_count -1
end
end
next if not direct_use_count > 1
direct_uses.each do |direct_use|
#clone and hookup design spec OA
space_type_source = direct_use.to_SpaceType
if not space_type_source.empty?
space_type_source = space_type_source.get
cloned_object = design_spec_outdoor_air_object.clone
space_type_source.setDesignSpecificationOutdoorAir(cloned_object.to_DesignSpecificationOutdoorAir.get)
original_cloned = true
end
space_source = direct_use.to_Space
if not space_source.empty?
space_source = space_source.get
cloned_object = design_spec_outdoor_air_object.clone
space_source.setDesignSpecificationOutdoorAir(cloned_object.to_DesignSpecificationOutdoorAir.get)
original_cloned = true
end
end #end of direct_uses.each do
#delete the now unused design spec OA
if original_cloned
runner.registerInfo("Making shared object #{design_spec_outdoor_air_object.name} unique.")
design_spec_outdoor_air_object.remove
end
end #end of design_spec_outdoor_air_objects.each do
#def to alter performance and life cycle costs of objects
def alter_performance(object, design_spec_outdoor_air_reduction_percent, runner)
#edit instance based on percentage reduction
instance = object
#not checking if fields are empty because these are optional like values for space infiltration are.
new_outdoor_air_per_person = instance.setOutdoorAirFlowperPerson(instance.outdoorAirFlowperPerson - instance.outdoorAirFlowperPerson*design_spec_outdoor_air_reduction_percent*0.01)
new_outdoor_air_per_floor_area = instance.setOutdoorAirFlowperFloorArea(instance.outdoorAirFlowperFloorArea - instance.outdoorAirFlowperFloorArea*design_spec_outdoor_air_reduction_percent*0.01)
new_outdoor_air_ach = instance.setOutdoorAirFlowAirChangesperHour(instance.outdoorAirFlowAirChangesperHour - instance.outdoorAirFlowAirChangesperHour*design_spec_outdoor_air_reduction_percent*0.01)
end #end of def alter_performance()
#array of instances to change
instances_array = []
#loop through space types
space_types.each do |space_type|
next if not space_type.spaces.size > 0
instances_array << space_type.designSpecificationOutdoorAir
end #end space types each do
#get spaces in model
if apply_to_building
spaces = model.getSpaces
else
if not space_type.spaces.empty?
spaces = space_type.spaces #only run on a single space type
end
end
spaces.each do |space|
instances_array << space.designSpecificationOutdoorAir
end #end of loop through spaces
instance_processed = []
instances_array.each do |instance|
next if instance.empty?
instance = instance.get
#only continue if this instance has not been processed yet
next if instance_processed.include? instance
instance_processed << instance
#call def to alter performance and life cycle costs
alter_performance(instance, design_spec_outdoor_air_reduction_percent, runner)
#rename
updated_instance_name = instance.setName("#{instance.name} (#{design_spec_outdoor_air_reduction_percent} percent reduction)")
altered_instances += 1
end
if altered_instances == 0
runner.registerAsNotApplicable("No design specification outdoor air objects were found in the specified space type(s).")
end
#report final condition
affected_area_ip = OpenStudio::convert(affected_area_si,"m^2","ft^2").get
runner.registerFinalCondition("#{altered_instances} design specification outdoor air objects in the model were altered affecting #{neat_numbers(affected_area_ip,0)}(ft^2).")
return true
end #end the run method
end #end the measure
#this allows the measure to be use by the application
ReduceVentilationByPercentage.new.registerWithApplication | 43.70566 | 203 | 0.756346 |
39fa6f65b5cea1980052c22ffde70d725534550d | 40 | class WatchList < ApplicationRecord
end
| 13.333333 | 35 | 0.85 |
382141b89f91aaf510839e750d62492178bea8bb | 811 | require "websocket/driver"
module ActionCable
module Connection
# Wrap the real socket to minimize the externally-presented API
class WebSocket
def initialize(env, event_target, event_loop, protocols: ActionCable::INTERNAL[:protocols])
@websocket = ::WebSocket::Driver.websocket?(env) ? ClientSocket.new(env, event_target, event_loop, protocols) : nil
end
def possible?
websocket
end
def alive?
websocket && websocket.alive?
end
def transmit(data)
websocket.transmit data
end
def close
websocket.close
end
def protocol
websocket.protocol
end
def rack_response
websocket.rack_response
end
protected
attr_reader :websocket
end
end
end
| 20.275 | 123 | 0.638718 |
f89719587141a5625e2a4d4e4dd12163b08eecf8 | 2,719 | # frozen_string_literal: true
class AssignmentRepo < ApplicationRecord
update_index("assignment_repo#assignment_repo") { self }
# TODO: remove this enum (dead code)
enum configuration_state: %i[not_configured configuring configured]
belongs_to :assignment
belongs_to :repo_access, optional: true
belongs_to :user
has_one :organization, -> { unscope(where: :deleted_at) }, through: :assignment
validates :assignment, presence: true
validates :github_repo_id, presence: true
validates :github_repo_id, uniqueness: true
validate :assignment_user_key_uniqueness
# TODO: Remove this dependency from the model.
before_destroy :silently_destroy_github_repository
delegate :creator, :starter_code_repo_id, to: :assignment
delegate :github_user, to: :user
delegate :default_branch, :commits, to: :github_repository
# This should really be in a view model
# but it'll live here for now.
def disabled?
@disabled ||= !github_repository.on_github? || !github_user.on_github?
end
def private?
!assignment.public_repo?
end
def github_team_id
repo_access.present? ? repo_access.github_team_id : nil
end
def github_repository
@github_repository ||= GitHubRepository.new(organization.github_client, github_repo_id)
end
def import_status
return "No starter code provided" unless assignment.starter_code?
github_repository.import_progress.status.humanize
end
# Public: This method is used for legacy purposes
# until we can get the transition finally completed
#
# NOTE: We used to create one person teams for Assignments,
# however when the new organization permissions came out
# https://github.com/blog/2020-improved-organization-permissions
# we were able to move these students over to being an outside collaborator
# so when we deleted the AssignmentRepo we would remove the student as well.
#
# Returns the User associated with the AssignmentRepo
alias original_user user
def user
original_user || repo_access.user
end
private
# Internal: Attempt to destroy the GitHub repository.
#
# Returns true.
def silently_destroy_github_repository
return true if organization.blank?
organization.github_organization.delete_repository(github_repo_id)
true
rescue GitHub::Error
true
end
# Internal: Validate uniqueness of <user, assignment> key.
# Only runs the validation on new records.
#
def assignment_user_key_uniqueness
return if persisted?
return unless AssignmentRepo.find_by(user: user, assignment: assignment)
errors.add(:assignment, "Should only have one assignment repository for each user-assignment combination")
end
end
| 29.879121 | 110 | 0.755057 |
bbbaf09caaa9e1c66b265e9ba853c4c6cdeed438 | 395 | class FixStudentExerciseAssignmentExerciseIndexUniqueness < ActiveRecord::Migration
def up
add_index :student_exercises, [:assignment_exercise_id, :student_assignment_id], :unique => true, :name => "index_student_exercises_on_assignment_exercise_scoped"
end
def down
remove_index :student_exercises, :name => "index_student_exercises_on_assignment_exercise_scoped"
end
end
| 39.5 | 170 | 0.810127 |
62de4d832d2f3508481682b74a28c9a07d075a04 | 267 | module Ruy
module Conditions
# Expects that at least one of the sub-conditions is be satisfied.
class Any < CompoundCondition
def call(ctx)
conditions.any? do |condition|
condition.call(ctx)
end
end
end
end
end
| 17.8 | 70 | 0.625468 |
181edeefd65622195022a6d01c329c868572e853 | 192 | class CreateTableReport < ActiveRecord::Migration[5.1]
def change
create_table :reports do |t|
t.string :date
t.integer :no_of_profiles
t.timestamps
end
end
end
| 17.454545 | 54 | 0.671875 |
e9e3486c543df1979ad1f4b5c0270b6789e6a68e | 122 | require 'spree_core'
require 'spree_experience_marketplace/engine'
require 'stripe'
require 'spree_experience_drop_ship'
| 20.333333 | 45 | 0.852459 |
1d51fcb71cc2b40d1f08c76f8a4c1253980da413 | 9,306 | # frozen_string_literal: true
require 'spec_helper'
require 'et_azure_insights/adapters/rack'
require 'et_azure_insights'
require 'rack/mock'
RSpec.describe EtAzureInsights::Adapters::Rack do
include_context 'fake client'
let(:fake_app_response) { [200, {}, 'app-body'] }
let(:fake_app) { spy('Rack app', call: fake_app_response) }
let(:fake_request_env) { Rack::MockRequest.env_for('http://www.dummy.com/endpoint?test=1') }
subject(:rack) { described_class.new(fake_app) }
describe '#call' do
it 'calls the app' do
rack.call(fake_request_env, client: fake_client)
expect(fake_app).to have_received(:call).with(fake_request_env)
end
it 'returns what the app returns' do
result = rack.call(fake_request_env, client: fake_client)
expect(result).to eq fake_app_response
end
it 'calls track_request on the telemetry client' do
rack.call(fake_request_env, client: fake_client)
expect(fake_client).to have_received(:track_request)
end
it 'calls track_request with the correct request id' do
rack.call(fake_request_env, client: fake_client)
expect(fake_client).to have_received(:track_request).with(match(/\A\|[0-9a-f]{32}\.[0-9a-f]{16}\.\z/), anything, anything, anything, anything, anything)
end
it 'calls track_request with the correct status' do
rack.call(fake_request_env, client: fake_client)
expect(fake_client).to have_received(:track_request).with(anything, anything, anything, '200', anything, anything)
end
context 'with string status code' do
let(:fake_app_response) { ['200', {}, 'app-body'] }
it 'calls track_request with the correct status' do
rack.call(fake_request_env, client: fake_client)
expect(fake_client).to have_received(:track_request).with(anything, anything, anything, '200', anything, anything)
end
end
context 'with non numeric string status code' do
let(:fake_app_response) { ['wrongvalue', {}, 'app-body'] }
it 'calls track_request with zero status' do
rack.call(fake_request_env, client: fake_client)
expect(fake_client).to have_received(:track_request).with(anything, anything, anything, '0', anything, anything)
end
end
it 'calls track_request with the correct operation id' do
expect(fake_app).to receive(:call) do |env|
expect(fake_client_operation).to have_received(:id=).with(match(/\A\|[0-9a-f]{32}\./))
fake_app_response
end
rack.call(fake_request_env, client: fake_client)
end
it 'calls track_request with the correct operation id supplied from ActionDispatch::RequestId middleware if in use in rails or similar environment' do
expect(fake_app).to receive(:call) do |env|
expect(fake_client_operation).to have_received(:id=).with('|c1b40e908df64ed1b27e4344c2557642.')
fake_app_response
end
rack.call(fake_request_env.merge('action_dispatch.request_id' => 'c1b40e90-8df6-4ed1-b27e-4344c2557642'), client: fake_client)
end
it 'sets the operation parent id set to the request id' do
expected_request_id = nil
expect(fake_app).to receive(:call) do |env|
expect(fake_client_operation).to have_received(:parent_id=) do |val|
expected_request_id = val
end
fake_app_response
end
subject.call(fake_request_env, client: fake_client)
expect(fake_client).to have_received(:track_request).with(expected_request_id, anything, anything, anything, anything, anything)
end
it 'calls track_request with the correct operation name' do
expect(fake_app).to receive(:call) do |env|
expect(fake_client_operation).to have_received(:name=).with('GET /endpoint')
fake_app_response
end
rack.call(fake_request_env, client: fake_client)
end
context 'error handling when error is raised in app' do
it 'calls track_exception on the telemetry client with the exception if the app raises an exception' do
allow(fake_app).to receive(:call).and_raise(RuntimeError, 'Fake error message')
begin
rack.call(fake_request_env, client: fake_client)
rescue StandardError
RuntimeError
end
expect(fake_client).to have_received(:track_exception)
.with(an_instance_of(RuntimeError).and(have_attributes(message: 'Fake error message')),)
end
it 'calls track_exception on the telemetry client with the correct context if the app raises an exception' do
allow(fake_app).to receive(:call).and_raise(RuntimeError, 'Fake error message')
begin
rack.call(fake_request_env, client: fake_client)
rescue StandardError
RuntimeError
end
expect(fake_client_operation).to have_received(:id=).with(match(/\A\|[0-9a-f]{32}\./)).at_least(:once)
expect(fake_client).to have_received(:track_exception)
end
it 'calls track_request on the telemetry client even after an exception but with success of false' do
allow(fake_app).to receive(:call).and_raise(RuntimeError, 'Fake error message')
begin
rack.call(fake_request_env, client: fake_client)
rescue StandardError
RuntimeError
end
expect(fake_client).to have_received(:track_request).with(anything, anything, anything, '500', false, anything)
end
it 're raises the original exception' do
allow(fake_app).to receive(:call).and_raise(RuntimeError, 'Fake error message')
expect { rack.call(fake_request_env, client: fake_client) }.to raise_exception(RuntimeError, 'Fake error message')
end
it 'keeps the original current span from before the call' do
allow(fake_app).to receive(:call).and_raise(RuntimeError, 'Fake error message')
original_span = EtAzureInsights::Correlation::Span.current
begin
rack.call(fake_request_env, client: fake_client)
rescue StandardError
RuntimeError
end
expect(EtAzureInsights::Correlation::Span.current).to be original_span
end
end
context 'error handling when error has been caught upstream so is not raised' do
let(:fake_app_response) { [500, {}, 'Fake error message'] }
it 'calls track_exception on the telemetry client with the exception if the app raises an exception' do
rack.call(fake_request_env, client: fake_client)
expect(fake_client).to have_received(:track_exception)
.with(an_instance_of(RuntimeError).and(have_attributes(message: 'Fake error message')))
end
it 'calls track_exception on the telemetry client with the correct context if the app raises an exception' do
rack.call(fake_request_env, client: fake_client)
expect(fake_client_operation).to have_received(:id=).with(match(/\A\|[0-9a-f]{32}\./)).at_least(:once)
expect(fake_client).to have_received(:track_exception)
end
it 'calls track_request on the telemetry client even after an exception but with success of false' do
rack.call(fake_request_env, client: fake_client)
expect(fake_client).to have_received(:track_request).with(anything, anything, anything, '500', false, anything)
end
it 'keeps the original current span from before the call' do
original_span = EtAzureInsights::Correlation::Span.current
rack.call(fake_request_env, client: fake_client)
expect(EtAzureInsights::Correlation::Span.current).to be original_span
end
end
context 'with traceparent header set suggesting this has been called by something else' do
# Some rules
# The request id contains |<root>.<parent>.<this-request-id>.
# The operation id is just |<root>|
# The parent id for the operation is |<root>.<parent>.
let(:fake_traceparent) { '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01' }
let(:fake_request_env) { Rack::MockRequest.env_for('http://www.dummy.com/endpoint?test=1', 'HTTP_TRACEPARENT' => fake_traceparent) }
it 'calls track_dependency with the current operation data set' do
rack.call(fake_request_env, client: fake_client)
expect(fake_client_operation).to have_received(:id=).with('|4bf92f3577b34da6a3ce929d0e0e4736.').at_least(:once)
expect(fake_client_operation).to have_received(:parent_id=).with('|4bf92f3577b34da6a3ce929d0e0e4736.00f067aa0ba902b7.')
expect(fake_client_operation).to have_received(:name=).with('GET /endpoint').at_least(:once)
expect(fake_client).to have_received(:track_request)
end
it 'calls track_dependency with the request id in the correct format' do
rack.call(fake_request_env, client: fake_client)
expect(fake_client).to have_received(:track_request).with(match(/\A\|[0-9a-f]{32}\.[0-9a-f]{16}\.\z/), anything, anything, anything, anything, anything)
end
it 'calls track_dependency with the request id that does not end with the parent' do
rack.call(fake_request_env, client: fake_client)
expect(fake_client).to have_received(:track_request).with(satisfy {|s| !s.end_with?('00f067aa0ba902b7.')}, anything, anything, anything, anything, anything)
end
end
end
end
| 43.083333 | 164 | 0.702557 |
7984c6b377869594f5993266e503b3bf46728ce2 | 1,129 | cask "microsoft-teams" do
version "1.4.00.29477"
sha256 "eef61e062ffcd9f843cffd41064ef0e73fa4e9da35245ec23c49452aead55075"
url "https://statics.teams.cdn.office.net/production-osx/#{version}/Teams_osx.pkg",
verified: "statics.teams.cdn.office.net"
name "Microsoft Teams"
desc "Meet, chat, call, and collaborate in just one place"
homepage "https://teams.microsoft.com/downloads"
livecheck do
url "https://aka.ms/teamsmac"
strategy :header_match
end
auto_updates true
pkg "Teams_osx.pkg"
uninstall pkgutil: "com.microsoft.teams",
launchctl: "com.microsoft.teams.TeamsUpdaterDaemon"
zap trash: [
"/Library/Logs/Microsoft/Teams",
"/Library/Preferences/com.microsoft.teams.plist",
"~/Library/Application Support/Microsoft/Teams",
"~/Library/Application Support/com.microsoft.teams",
"~/Library/Caches/com.microsoft.teams",
"~/Library/Cookies/com.microsoft.teams.binarycookies",
"~/Library/Logs/Microsoft Teams",
"~/Library/Preferences/com.microsoft.teams.plist",
"~/Library/Saved Application State/com.microsoft.teams.savedState",
]
end
| 32.257143 | 85 | 0.723649 |
1a9fe69ec58c031bab114898678bd82406ac7232 | 1,241 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'c21e'
s.version = '2.0.0'
s.authors = ["Aslak Hellesøy"]
s.description = 'Run cross-platform executables'
s.summary = "#{s.name}-#{s.version}"
s.email = '[email protected]'
s.homepage = "https://github.com/cucumber/cucumber-expressions-ruby#readme"
s.platform = Gem::Platform::RUBY
s.license = "MIT"
s.required_ruby_version = ">= 2.3"
s.metadata = {
'bug_tracker_uri' => 'https://github.com/cucumber/cucumber/issues',
'documentation_uri' => 'https://www.rubydoc.info/github/cucumber/c21e-ruby',
'mailing_list_uri' => 'https://groups.google.com/forum/#!forum/cukes',
'source_code_uri' => 'https://github.com/cucumber/cucumber/blob/master/c21e/ruby',
}
s.add_development_dependency 'rake', '~> 13.0', '>= 13.0.1'
s.add_development_dependency 'rspec', '~> 3.9', '>= 3.9.0'
s.rubygems_version = ">= 1.6.1"
s.files = Dir[
'README.md',
'LICENSE',
'lib/**/*',
]
s.test_files = Dir['spec/**/*']
s.rdoc_options = ["--charset=UTF-8"]
s.require_path = "lib"
end
| 36.5 | 104 | 0.560032 |
1ceefbf470accc2beb263125b654d614dd93e0cb | 628 | # frozen_string_literal: true
require 'geocoder/lookups/baidu'
require 'geocoder/results/baidu_ip'
module Geocoder
module Lookup
class BaiduIp < Baidu
def name
'Baidu IP'
end
private # ---------------------------------------------------------------
def base_query_url(_query)
"#{protocol}://api.map.baidu.com/location/ip?"
end
def content_key
'content'
end
def query_url_params(query)
{
ip: query.sanitized_text,
ak: configuration.api_key,
coor: 'bd09ll'
}.merge(super)
end
end
end
end
| 19.030303 | 79 | 0.525478 |
2192b0529d678dc62b69352a28e9ac1da253b7c4 | 3,746 | require 'spec_helper'
describe Spree::Price, type: :model do
describe 'searchable columns' do
subject { described_class.whitelisted_ransackable_attributes }
it 'allows searching by variant_id' do
expect(subject).to include("variant_id")
end
end
describe 'validations' do
let(:variant) { stub_model Spree::Variant }
subject { Spree::Price.new variant: variant, amount: amount }
context 'when the amount is nil' do
let(:amount) { nil }
it { is_expected.to be_valid }
end
context 'when the amount is less than 0' do
let(:amount) { -1 }
it 'has 1 error_on' do
expect(subject.error_on(:amount).size).to eq(1)
end
it 'populates errors' do
subject.valid?
expect(subject.errors.messages[:amount].first).to eq 'must be greater than or equal to 0'
end
end
context 'when the amount is greater than maximum amount' do
let(:amount) { Spree::Price::MAXIMUM_AMOUNT + 1 }
it 'has 1 error_on' do
expect(subject.error_on(:amount).size).to eq(1)
end
it 'populates errors' do
subject.valid?
expect(subject.errors.messages[:amount].first).to eq "must be less than or equal to #{Spree::Price::MAXIMUM_AMOUNT}"
end
end
context 'when the amount is between 0 and the maximum amount' do
let(:amount) { Spree::Price::MAXIMUM_AMOUNT }
it { is_expected.to be_valid }
end
context '#country_iso' do
subject(:price) { build(:price, country_iso: country_iso) }
context 'when country iso is nil' do
let(:country_iso) { nil }
it { is_expected.to be_valid }
end
context 'when country iso is a country code' do
let!(:country) { create(:country, iso: "DE") }
let(:country_iso) { "DE" }
it { is_expected.to be_valid }
end
context 'when country iso is not a country code' do
let(:country_iso) { "ZZ" }
it { is_expected.not_to be_valid }
end
end
describe '#country' do
let!(:country) { create(:country, iso: "DE") }
let(:price) { create(:price, country_iso: "DE", is_default: false) }
it 'returns the country object' do
expect(price.country).to eq(country)
end
end
end
describe "#currency" do
let(:variant) { stub_model Spree::Variant }
subject { Spree::Price.new variant: variant, amount: 10, currency: currency }
describe "validation" do
context "with an invalid currency" do
let(:currency) { "XYZ" }
it { is_expected.to be_invalid }
it "has an understandable error message" do
subject.valid?
expect(subject.errors.messages[:currency].first).to eq("is not a valid currency code")
end
end
context "with a valid currency" do
let(:currency) { "USD" }
it { is_expected.to be_valid }
end
end
end
describe 'scopes' do
describe '.for_any_country' do
let(:country) { create(:country) }
let!(:fallback_price) { create(:price, country_iso: nil) }
let!(:country_price) { create(:price, country: country) }
subject { described_class.for_any_country }
it { is_expected.to include(fallback_price) }
end
end
describe 'net_amount' do
let(:country) { create(:country, iso: "DE") }
let(:zone) { create(:zone, countries: [country]) }
let!(:tax_rate) { create(:tax_rate, included_in_price: true, zone: zone, tax_category: variant.tax_category) }
let(:variant) { create(:product).master }
let(:price) { variant.prices.create(amount: 20, country: country) }
subject { price.net_amount }
it { is_expected.to eq(BigDecimal.new(20) / 1.1) }
end
end
| 28.378788 | 124 | 0.627336 |
281c54a0d0dd153d7bc3a05bb79d8ec540a9e511 | 1,400 | module OpenActive
module Models
module Schema
class MusicGroup < ::OpenActive::Models::Schema::PerformingGroup
# @!attribute type
# @return [String]
def type
"schema:MusicGroup"
end
# @return [OpenActive::Models::Schema::MusicAlbum]
define_property :album, as: "album", types: [
"OpenActive::Models::Schema::MusicAlbum",
]
# @return [OpenActive::Models::Schema::MusicRecording]
define_property :tracks, as: "tracks", types: [
"OpenActive::Models::Schema::MusicRecording",
]
# @return [String,URI]
define_property :genre, as: "genre", types: [
"string",
"URI",
]
# @return [OpenActive::Models::Schema::ItemList,OpenActive::Models::Schema::MusicRecording]
define_property :track, as: "track", types: [
"OpenActive::Models::Schema::ItemList",
"OpenActive::Models::Schema::MusicRecording",
]
# @return [OpenActive::Models::Schema::Person]
define_property :music_group_member, as: "musicGroupMember", types: [
"OpenActive::Models::Schema::Person",
]
# @return [OpenActive::Models::Schema::MusicAlbum]
define_property :albums, as: "albums", types: [
"OpenActive::Models::Schema::MusicAlbum",
]
end
end
end
end
| 30.434783 | 99 | 0.583571 |
287952fa3f83856a6824e7277798a6b0492f7994 | 1,362 | require 'rails_helper'
describe TimeMachine do
let!(:commodity1) { create :commodity, validity_start_date: Time.now.ago(1.day),
validity_end_date: Time.now.in(1.day) }
let!(:commodity2) { create :commodity, validity_start_date: Time.now.ago(20.days),
validity_end_date: Time.now.ago(10.days) }
describe '.at' do
it 'sets date to current date if argument is blank' do
TimeMachine.at(nil) {
expect(Commodity.actual.all).to include commodity1
expect(Commodity.actual.all).to_not include commodity2
}
end
it 'sets date to current date if argument is errorenous' do
TimeMachine.at("#&$*(#)") {
expect(Commodity.actual.all).to include commodity1
expect(Commodity.actual.all).to_not include commodity2
}
end
it 'parses and sets valid date from argument' do
TimeMachine.at(Time.now.ago(15.days).to_s) {
expect(Commodity.actual.all).to_not include commodity1
expect(Commodity.actual.all).to include commodity2
}
end
end
describe '.now' do
it 'sets date to current date' do
TimeMachine.now {
expect(Commodity.actual.all).to include commodity1
expect(Commodity.actual.all).to_not include commodity2
}
end
end
end
| 33.219512 | 84 | 0.632159 |
083dd7ef85ef7d2df75b4778428de7626ade416b | 135 | module Gowk
module VERSION #:nodoc:
MAJOR = 0
MINOR = 0
TINY = 1
STRING = [MAJOR, MINOR, TINY].join('.')
end
end
| 13.5 | 43 | 0.555556 |
79a234b276339942875b0cf97eb285fa978894f1 | 1,670 | class Lighthouse < Formula
desc "Rust Ethereum 2.0 Client"
homepage "https://github.com/sigp/lighthouse"
url "https://github.com/sigp/lighthouse/archive/refs/tags/v2.1.2.tar.gz"
sha256 "53db198ceba81229ec2a7b44e48e20cb211c178d5026c4856636ef97ce5b5834"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "e2834155e6520c697b58a27da27f7cf2729c301832df1b087ee328068a2ca066"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "15a3e92173a3b262e282225caefe3db8e20cc8db2c0f391657b4c3ec545607d0"
sha256 cellar: :any_skip_relocation, monterey: "96beb6c6e3d17685025065307cbd9b21926e0a99312232b580658cdf41be8744"
sha256 cellar: :any_skip_relocation, big_sur: "52384ced9451f10e2658b179e71a11f0586d8987499d889731c14151b49a88fb"
sha256 cellar: :any_skip_relocation, catalina: "182aa62fb0196a285e7600358fe29b59faedba54c5427f21f4cb97884c3fd90e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "ebf23495555201d5a998fdf0ee2712e3d564d4c94affe1312d17cf6c2d303455"
end
depends_on "cmake" => :build
depends_on "rust" => :build
uses_from_macos "zlib"
on_linux do
depends_on "llvm" => :build
end
def install
system "cargo", "install", *std_cargo_args(path: "./lighthouse")
end
test do
assert_match "Lighthouse", shell_output("#{bin}/lighthouse --version")
http_port = free_port
fork do
exec bin/"lighthouse", "beacon_node", "--http", "--http-port=#{http_port}", "--port=#{free_port}"
end
sleep 10
output = shell_output("curl -sS -XGET http://127.0.0.1:#{http_port}/eth/v1/node/syncing")
assert_match "is_syncing", output
end
end
| 38.837209 | 123 | 0.758683 |
abf6bf01f7dc00532b9c7de0d020a2a444ab6981 | 1,623 | # encoding: utf-8
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# /spec/fixtures/responses/whois.cmc.iq/status_available.expected
#
# and regenerate the tests with the following rake task
#
# $ rake spec:generate
#
require 'spec_helper'
require 'whois/record/parser/whois.cmc.iq.rb'
describe Whois::Record::Parser::WhoisCmcIq, "status_available.expected" do
subject do
file = fixture("responses", "whois.cmc.iq/status_available.txt")
part = Whois::Record::Part.new(body: File.read(file))
described_class.new(part)
end
describe "#domain" do
it do
expect(subject.domain).to eq("u34jedzcq.iq")
end
end
describe "#domain_id" do
it do
expect(subject.domain_id).to eq(nil)
end
end
describe "#status" do
it do
expect(subject.status).to eq(:available)
end
end
describe "#available?" do
it do
expect(subject.available?).to eq(true)
end
end
describe "#registered?" do
it do
expect(subject.registered?).to eq(false)
end
end
describe "#created_on" do
it do
expect(subject.created_on).to eq(nil)
end
end
describe "#updated_on" do
it do
expect(subject.updated_on).to eq(nil)
end
end
describe "#expires_on" do
it do
expect(subject.expires_on).to eq(nil)
end
end
describe "#registrar" do
it do
expect(subject.registrar).to eq(nil)
end
end
describe "#nameservers" do
it do
expect(subject.nameservers).to be_a(Array)
expect(subject.nameservers).to eq([])
end
end
end
| 21.355263 | 74 | 0.663586 |
e9de2ca50dba9739c71fba2d27cbced09b739b10 | 1,311 | # Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not
# use this file except in compliance with the License. A copy of the License is
# located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
Given(/^a TableConfig of:$/) do |code_block|
TableConfigTestModel = @model
@table_config = eval(code_block)
end
When(/^we migrate the TableConfig$/) do
@table_config.migrate!
end
Then(/^the TableConfig should be compatible with the remote table$/) do
expect(@table_config.compatible?).to be_truthy
end
Then(/^the TableConfig should be an exact match with the remote table$/) do
expect(@table_config.exact_match?).to be_truthy
end
Then(/^the TableConfig should not be compatible with the remote table$/) do
expect(@table_config.compatible?).to be_falsy
end
Given(/^we add a global secondary index to the model with definition:$/) do |gsi|
index_name, opts = eval(gsi)
@model.global_secondary_index(index_name, opts)
end
| 33.615385 | 81 | 0.754386 |
bf256b1eb9684cb5563842e0720f0170bb554e2d | 813 | require_relative '../core'
require_relative '../errors'
module Erlen; module Schema
# This class represents a derived attribute defined in a Schema class. An
# attribute keeps track of its name, type, and a attribute specific block to
# derive the value.
class DerivedAttribute
# The name of the attribute
attr_accessor :name
# The type of the attribute
attr_accessor :type
# Attribute specific block to derive value
attr_accessor :derived_block
def initialize(name, type, blk)
self.name = name.to_s
self.type = type
self.derived_block = blk # proc object
end
# Derives the value using attribute-specific block.
#
# @param schema [Object] schema object
def derive_value(schema)
derived_block.call(schema)
end
end
end; end
| 25.40625 | 78 | 0.698647 |
bbafda7fb3a3cca1ddf6af26e2119073b70fc8a5 | 175 | # frozen_string_literal: true
FactoryBot.define do
factory :drink do
sequence(:name) { |n| "drink_#{n}" }
quantity_stock { 3 }
maker
organization
end
end
| 15.909091 | 40 | 0.657143 |
e8796f3319cc6322ed5b61f35e61922d6233f7ee | 848 | # frozen_string_literal: ture
require "test_helper"
module Graphql
module Voyager
module Rails
class ConfigTest < ActiveSupport::TestCase
class MockViewContext
def form_authenticity_token
"abc-123"
end
end
setup do
@config = Graphql::Voyager::Rails::Config.new
@view_context = MockViewContext.new
end
test "it adds CSRF header if requested" do
assert_equal "abc-123", @config.resolve_headers(@view_context)["X-CSRF-Token"]
@config.csrf = false
assert_nil @config.resolve_headers(@view_context)["X-CSRF-Token"]
end
test "it adds JSON header by default" do
assert_equal "application/json", @config.resolve_headers(@view_context)["Content-Type"]
end
end
end
end
end
| 25.69697 | 97 | 0.625 |
21800cbbc14d97f438e91fd9baebe42f14455c38 | 3,564 | require 'chef'
#require 'pp'
class Rack_awareness
class By_switch
def initialize(node)
@node=node
@rr_counter=0
@switch_list = self.get_switch_list()
@switch_list = self.switch_to_zone() if @switch_list.size != 0
end
def get_switch_list()
switch_list=Hash.new()
#get all swift nodes
env_filter = " AND swift_config_environment:#{@node[:swift][:config][:environment]}"
nodes = Chef::Search::Query.new.search(:node, "roles:swift-storage#{env_filter}")[0]
#PP.pp(nodes.size, $>, 40)
nodes.each do |n|
sw_name=self.get_node_sw(n)
if sw_name == -1
next
end
if switch_list["#{sw_name}"].nil?
switch_list["#{sw_name}"]=Hash.new()
switch_list["#{sw_name}"]["nodes"]=[]
end
if not switch_list["#{sw_name}"]["nodes"].include?(n.name)
switch_list["#{sw_name}"]["nodes"] << n.name
end
end
return switch_list
end
def get_node_sw(n)
#get switch for storage iface
storage_ip = Swift::Evaluator.get_ip_by_type(n, :storage_ip_expr)
#get storage iface
iface=""
n[:network][:interfaces].keys.each do |ifn|
if n[:network][:interfaces]["#{ifn}"][:addresses].has_key?(storage_ip)
iface=ifn
break
end
end
#this may lead us to eth0, or eth0.123, or even br0, br0.123, vlan231 and so on, so
#TODO: some cases for complicated network configuration with bridges, vlans
case iface
when /eth[0-9]*.*/
iface=iface[/^eth[0-9]*/]
else
#fallback to something default
iface=n[:crowbar_ohai][:switch_config].keys[0]
end
sw_name=n[:crowbar_ohai][:switch_config][iface][:switch_name]
end
def switch_to_zone()
#set switch to zone by round-robin
zone_count=@node[:swift][:zones]
zone_list=zone_count.times.to_a
switch_list=@switch_list
switch_list.keys.each do |sw_name|
switch_list["#{sw_name}"]["zones"]=[] if not switch_list["#{sw_name}"].has_key?("zones")
end
if switch_list.size >= zone_list.size
#some switches may have same zone with each other
switch_list.keys.sort.each do |sw_name|
zone=zone_list.shift
zone_list=zone_count.times.to_a if zone_list.size == 0
switch_list["#{sw_name}"]["zones"] << zone
end
else
#some switches may have more than 1 zone
sw_iter=switch_list.keys.sort
zone_list.each do |zone|
sw_name=sw_iter.shift
sw_iter=switch_list.keys.sort if sw_iter.size == 0
switch_list["#{sw_name}"]["zones"] << zone
end
end
return switch_list
end
def node_to_zone(params)
n=params[:target_node]
sw_name=self.get_node_sw(n)
zone_count=@node[:swift][:zones]
if sw_name == -1
#just assign to somewhere
zone=@rr_counter % zone_count
@rr_counter += 1
return zone
end
available_zones=@switch_list["#{sw_name}"]["zones"]
zone=@rr_counter % available_zones.size
zone=available_zones[zone]
@rr_counter += 1
return zone
end
end
end
| 32.697248 | 101 | 0.547419 |
1d5b91bd08e707412d0489429dd520ff1b73550e | 102 | module RCRM
class Sources < Collection
def default_fields
[Source.new]
end
end
end
| 11.333333 | 28 | 0.656863 |
03b4ebf83e4dada89ff97beb4c68034043b615cb | 2,764 | module Departure
# Executes the given command returning it's status and errors
class Command
COMMAND_NOT_FOUND = 127
# Constructor
#
# @param command_line [String]
# @param error_log_path [String]
# @param logger [#write_no_newline]
def initialize(command_line, error_log_path, logger)
@command_line = command_line
@error_log_path = error_log_path
@logger = logger
end
# Executes the command returning its status. It also prints its stdout to
# the logger and its stderr to the file specified in error_log_path.
#
# @raise [NoStatusError] if the spawned process' status can't be retrieved
# @raise [SignalError] if the spawned process received a signal
# @raise [CommandNotFoundError] if pt-online-schema-change can't be found
#
# @return [Process::Status]
def run
log_started
run_in_process
log_finished
validate_status!
status
end
private
attr_reader :command_line, :error_log_path, :logger, :status
# Runs the command in a separate process, capturing its stdout and
# execution status
def run_in_process
Open3.popen3(full_command) do |_stdin, stdout, _stderr, waith_thr|
begin
loop do
IO.select([stdout])
data = stdout.read_nonblock(8192)
logger.write_no_newline(data)
end
rescue EOFError # rubocop:disable Lint/HandleExceptions
# noop
ensure
@status = waith_thr.value
end
end
end
# Builds the actual command including stderr redirection to the specified
# log file
#
# @return [String]
def full_command
"#{command_line} 2> #{error_log_path}"
end
# Validates the status of the execution
#
# @raise [NoStatusError] if the spawned process' status can't be retrieved
# @raise [SignalError] if the spawned process received a signal
# @raise [CommandNotFoundError] if pt-online-schema-change can't be found
def validate_status!
raise SignalError.new(status) if status.signaled? # rubocop:disable Style/RaiseArgs
raise CommandNotFoundError if status.exitstatus == COMMAND_NOT_FOUND
raise Error, error_message unless status.success?
end
# Returns the error message that appeared in the process' stderr
#
# @return [String]
def error_message
File.read(error_log_path)
end
# Logs when the execution started
def log_started
logger.write("\n")
logger.say("Running #{command_line}\n\n", true)
end
# Prints a line break to keep the logs separate from the execution time
# print by the migration
def log_finished
logger.write("\n")
end
end
end
| 28.494845 | 89 | 0.667873 |
7aa31780b53c99c7ac7ec54d8c1c94f070910fb1 | 264 | Refinery::Core.configure do |config|
# Register extra javascript for backend
config.register_javascript "refinery/news/news.js"
config.register_javascript "refinery/page-image-picker.js"
config.register_stylesheet "refinery/page-image-picker.css"
end
| 33 | 62 | 0.791667 |
39fce255992c9971e1ccb1153abb7edf249fc29e | 2,098 | license = <<-EOF
Copyright (c) 2011, Tony Million.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
EOF
Pod::Spec.new do |s|
s.name = 'SRReachability'
s.version = '3.2'
s.summary = 'ARC and GCD Compatible Reachability Class for iOS and OS X. Drop in replacement for Apple Reachability.'
s.homepage = 'https://github.com/tonymillion/Reachability'
s.authors = { 'Tony Million' => '[email protected]' }
s.social_media_url = "http://twitter.com/tonymillion"
s.license = { :type => 'BSD', :text => license }
s.source = { :git => 'https://github.com/SecondRenaissance/SRReachability.git', :tag => "v#{s.version}" }
s.source_files = 'SRReachability.{h,m}'
s.framework = 'SystemConfiguration'
s.requires_arc = true
s.ios.deployment_target = "6.0"
s.osx.deployment_target = "10.8"
s.tvos.deployment_target = "9.0"
end
| 61.705882 | 755 | 0.749762 |
280255f875388cd9356a48807393cf1b56260e75 | 1,060 | module WinFFI
module Comctl32
buffer = [
:LISTVIEW_CLASSES, 0x00000001, # listview, header
:TREEVIEW_CLASSES, 0x00000002, # treeview, tooltips
:BAR_CLASSES, 0x00000004, # toolbar, statusbar, track
:TAB_CLASSES, 0x00000008, # tab, tooltips
:UPDOWN_CLASS, 0x00000010, # updown
:PROGRESS_CLASS, 0x00000020, # progress
:HOTKEY_CLASS, 0x00000040, # hotkey
:ANIMATE_CLASS, 0x00000080, # animate
:WIN95_CLASSES, 0x000000FF,
:DATE_CLASSES, 0x00000100, # month picker, date picker
:USEREX_CLASSES, 0x00000200, # comboex
:COOL_CLASSES, 0x00000400, # rebar (coolbar) control
:INTERNET_CLASSES, 0x00000800,
:PAGESCROLLER_CLASS, 0x00001000, # page scroller
:NATIVEFNTCTL_CLASS, 0x00002000, # native font control
]
buffer += [:STANDARD_CLASSES, 0x00004000, :LINK_CLASS, 0x00008000] if WINDOWS_VERSION >= :xp
InitCommonControls = enum :init_common_controls, buffer
end
end | 44.166667 | 96 | 0.641509 |
33e2baf9e72c346b705f2cc8933a626cecf5eab1 | 417 | cask "font-commissioner" do
version :latest
sha256 :no_check
url "https://github.com/google/fonts/raw/master/ofl/commissioner/Commissioner%5Bslnt%2Cwght%5D.ttf",
verified: "github.com/google/fonts/"
name "Commissioner"
desc "Low-contrast humanist sans-serif font with almost classical proportions"
homepage "https://fonts.google.com/specimen/Commissioner"
font "Commissioner[slnt,wght].ttf"
end
| 32.076923 | 102 | 0.760192 |
f74b26d7185b84630424ff01f3ac0412a4f7674a | 39 | module Version
VERSION = '0.2.0'
end
| 9.75 | 19 | 0.666667 |
91042a62a139d8b69e1f0f0eee12777f60009a87 | 1,544 | # Copyright (C) 2018 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
module Operation
class GetMore
# A MongoDB getMore operation sent as a command message.
#
# @api private
#
# @since 2.5.2
class Command
include Specifiable
include Executable
include Limited
include ReadPreferenceSupported
# Execute the operation.
#
# @example
# operation.execute(server)
#
# @param [ Mongo::Server ] server The server to send the operation to.
#
# @return [ Mongo::Operation::GetMore::Result ] The operation result.
#
# @since 2.5.2
def execute(server)
result = Result.new(dispatch_message(server))
process_result(result, server)
result.validate!
end
private
def message(server)
Protocol::Query.new(db_name, Database::COMMAND, command(server), options(server))
end
end
end
end
end
| 28.072727 | 91 | 0.639896 |
0804865aa6681d0402d79cbb2aade5eaa8e7a466 | 221 | class Apikitchen < Cask
url 'https://s3.amazonaws.com/envolto-static/ApiKitchen_0.1.dmg'
homepage 'http://apikitchen.com/'
version '0.1'
sha1 '682a2a6d670af612bac57e641f282f76ad65a325'
link 'ApiKitchen.app'
end
| 27.625 | 66 | 0.760181 |
3997777eaab6989224c7f50d18cc3edcd139f54d | 1,368 | module Fog
module Compute
class Ecloud
class Real
basic_request :get_catalog
end
class Mock
def get_catalog(catalog_uri)
catalog_uri = ensure_unparsed(catalog_uri)
xml = nil
if catalog = mock_data.catalog_from_href(catalog_uri)
builder = Builder::XmlMarkup.new
xml = builder.Catalog(xmlns.merge(
:type => "application/vnd.vmware.vcloud.catalog+xml",
:href => catalog.href,
:name => catalog.name
)) do |xml|
xml.CatalogItems do |xml|
catalog.items.each do |catalog_item|
xml.CatalogItem(
:type => "application/vnd.vmware.vcloud.catalogItem+xml",
:href => catalog_item.href,
:name => catalog_item.name
)
end
end
end
end
if xml
mock_it 200,
xml, { 'Content-Type' => 'application/vnd.vmware.vcloud.catalog+xml' }
else
mock_error 200, "401 Unauthorized"
end
end
end
end
end
end
| 30.4 | 99 | 0.434942 |
91ce6b8198c7b2d3a5b59830e6b2118f1a39ceaf | 6,388 |
# generated from template-files/ios/ExpoKit.podspec
folly_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1'
folly_compiler_flags = folly_flags + ' ' + '-Wno-comma -Wno-shorten-64-to-32'
folly_version = '2020.01.13.00'
boost_compiler_flags = '-Wno-documentation'
Pod::Spec.new do |s|
s.name = "ABI40_0_0ExpoKit"
s.version = "40.0.0"
s.summary = 'ExpoKit'
s.description = 'ExpoKit allows native projects to integrate with the Expo SDK.'
s.homepage = 'http://docs.expo.io'
s.license = 'MIT'
s.author = "650 Industries, Inc."
s.requires_arc = true
s.platform = :ios, "10.0"
s.default_subspec = "Core"
s.source = { :git => "http://github.com/expo/expo.git" }
s.xcconfig = {
'CLANG_CXX_LANGUAGE_STANDARD' => 'gnu++14',
'SYSTEM_HEADER_SEARCH_PATHS' => "\"$(PODS_ROOT)/boost-for-react-native\" \"$(PODS_ROOT)/Folly\" \"$(PODS_ROOT)/Headers/Private/React-Core\"",
'OTHER_CPLUSPLUSFLAGS' => [
"$(OTHER_CFLAGS)",
"-DFOLLY_NO_CONFIG",
"-DFOLLY_MOBILE=1",
"-DFOLLY_USE_LIBCPP=1"
]
}
s.pod_target_xcconfig = {
"USE_HEADERMAP" => "YES",
"HEADER_SEARCH_PATHS" => "\"$(PODS_TARGET_SRCROOT)/ReactCommon\" \"$(PODS_TARGET_SRCROOT)\" \"$(PODS_ROOT)/Folly\" \"$(PODS_ROOT)/boost-for-react-native\" \"$(PODS_ROOT)/DoubleConversion\" \"$(PODS_ROOT)/Headers/Private/React-Core\" "
}
s.compiler_flags = folly_compiler_flags + ' ' + boost_compiler_flags
s.xcconfig = {
"HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost-for-react-native\" \"$(PODS_ROOT)/glog\" \"$(PODS_ROOT)/Folly\" \"$(PODS_ROOT)/Headers/Private/ABI40_0_0React-Core\"",
"OTHER_CFLAGS" => "$(inherited)" + " " + folly_flags
}
s.subspec "Expo" do |ss|
ss.source_files = "Core/**/*.{h,m,mm,cpp}"
ss.dependency "ABI40_0_0React-Core"
ss.dependency "ABI40_0_0React-Core/DevSupport"
ss.dependency "ABI40_0_0ReactCommon"
ss.dependency "ABI40_0_0UMCore"
ss.dependency "ABI40_0_0UMReactNativeAdapter"
ss.dependency "ABI40_0_0EXAdsAdMob"
ss.dependency "ABI40_0_0EXAdsFacebook"
ss.dependency "ABI40_0_0EXAmplitude"
ss.dependency "ABI40_0_0EXSegment"
ss.dependency "ABI40_0_0EXAppAuth"
ss.dependency "ABI40_0_0EXAppleAuthentication"
ss.dependency "ABI40_0_0EXApplication"
ss.dependency "ABI40_0_0EXAV"
ss.dependency "ABI40_0_0EXBackgroundFetch"
ss.dependency "ABI40_0_0EXBarCodeScanner"
ss.dependency "ABI40_0_0EXBattery"
ss.dependency "ABI40_0_0EXBlur"
ss.dependency "EXBranch"
ss.dependency "ABI40_0_0EXBrightness"
ss.dependency "ABI40_0_0EXCalendar"
ss.dependency "ABI40_0_0EXCamera"
ss.dependency "ABI40_0_0EXCellular"
ss.dependency "ABI40_0_0EXConstants"
ss.dependency "ABI40_0_0EXContacts"
ss.dependency "ABI40_0_0EXCrypto"
ss.dependency "ABI40_0_0EXDevice"
ss.dependency "ABI40_0_0EXDocumentPicker"
ss.dependency "ABI40_0_0EXErrorRecovery"
ss.dependency "ABI40_0_0EXFaceDetector"
ss.dependency "ABI40_0_0EXFacebook"
ss.dependency "ABI40_0_0EXFileSystem"
ss.dependency "ABI40_0_0EXFirebaseAnalytics"
ss.dependency "ABI40_0_0EXFirebaseCore"
ss.dependency "ABI40_0_0EXFont"
ss.dependency "EXGL_CPP"
ss.dependency "ABI40_0_0EXGL"
ss.dependency "ABI40_0_0EXGoogleSignIn"
ss.dependency "ABI40_0_0EXHaptics"
ss.dependency "ABI40_0_0EXImageLoader"
ss.dependency "ABI40_0_0EXImageManipulator"
ss.dependency "ABI40_0_0EXImagePicker"
ss.dependency "ABI40_0_0EXKeepAwake"
ss.dependency "ABI40_0_0EXLinearGradient"
ss.dependency "ABI40_0_0EXLocalAuthentication"
ss.dependency "ABI40_0_0EXLocalization"
ss.dependency "ABI40_0_0EXLocation"
ss.dependency "ABI40_0_0EXMailComposer"
ss.dependency "ABI40_0_0EXMediaLibrary"
ss.dependency "ABI40_0_0EXNetwork"
ss.dependency "ABI40_0_0EXNotifications"
ss.dependency "ABI40_0_0EXPermissions"
ss.dependency "ABI40_0_0EXPrint"
ss.dependency "ABI40_0_0EXRandom"
ss.dependency "ABI40_0_0EXScreenCapture"
ss.dependency "ABI40_0_0EXScreenOrientation"
ss.dependency "ABI40_0_0EXSecureStore"
ss.dependency "ABI40_0_0EXSensors"
ss.dependency "ABI40_0_0EXSharing"
ss.dependency "ABI40_0_0EXSMS"
ss.dependency "ABI40_0_0EXSpeech"
ss.dependency "ABI40_0_0EXSplashScreen"
ss.dependency "ABI40_0_0EXSQLite"
ss.dependency "ABI40_0_0EXStoreReview"
ss.dependency "ABI40_0_0EXTaskManager"
ss.dependency "ABI40_0_0EXUpdates"
ss.dependency "ABI40_0_0EXVideoThumbnails"
ss.dependency "ABI40_0_0EXWebBrowser"
ss.dependency "ABI40_0_0UMAppLoader"
ss.dependency "ABI40_0_0UMBarCodeScannerInterface"
ss.dependency "ABI40_0_0UMCameraInterface"
ss.dependency "ABI40_0_0UMConstantsInterface"
ss.dependency "ABI40_0_0UMFaceDetectorInterface"
ss.dependency "ABI40_0_0UMFileSystemInterface"
ss.dependency "ABI40_0_0UMFontInterface"
ss.dependency "ABI40_0_0UMImageLoaderInterface"
ss.dependency "ABI40_0_0UMPermissionsInterface"
ss.dependency "ABI40_0_0UMSensorsInterface"
ss.dependency "ABI40_0_0UMTaskManagerInterface"
ss.dependency "Amplitude"
ss.dependency "Analytics"
ss.dependency "AppAuth"
ss.dependency "FBAudienceNetwork"
ss.dependency "GoogleSignIn"
ss.dependency "GoogleMaps"
ss.dependency "Google-Maps-iOS-Utils"
ss.dependency "lottie-ios"
ss.dependency "JKBigInteger2"
ss.dependency "Branch"
ss.dependency "Google-Mobile-Ads-SDK"
ss.dependency "RCT-Folly"
end
s.subspec "ExpoOptional" do |ss|
ss.dependency "ABI40_0_0ExpoKit/Expo"
ss.source_files = "Optional/**/*.{h,m,mm}"
end
end
| 44.361111 | 238 | 0.650595 |
33c9cb90f9824b32db8b183f23fdc1013dc8a0ed | 40,770 | # encoding: UTF-8
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
module ICU
class Tournament
describe Krause do
def check_player(num, first, last, other={})
p = @t.player(num)
expect(p.first_name).to eq(first)
expect(p.last_name).to eq(last)
[:gender, :title, :rating, :fide_rating, :fed, :id, :fide_id, :dob, :rank].each do |key|
expect(p.send(key)).to eq(other[key]) if other.has_key?(key)
end
end
def check_results(num, results, points)
p = @t.player(num)
expect(p.results.size).to eq(results)
expect(p.points).to eq(points)
end
context "a typical tournament" do
before(:all) do
krause = <<KRAUSE
012 Las Vegas National Open
022 Las Vegas
032 USA
042 2008.06.07
052 2008.06.09
062 3
072 3
082 1
092 All-Play-All
102 Hans Scmidt
112 Gerry Graham, Herbert Scarry
122 60 in 2hr, 30 in 1hr, rest in 1hr
013 Coaching Team 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
132 08.06.07 08.06.08 08.06.09
001 1 w Ui Laighleis,Gearoidin 1985 IRL 2501171 1964.06.10 1.0 2 2 b 0 3 w 1
001 2 m m Orr,Mark 2258 IRL 2500035 1955.11.09 2.0 1 1 w 1 3 b 1
001 3 m g Bologan,Viktor 2663 MDA 13900048 1971.01.01 0.0 3 1 b 0 2 w 0
KRAUSE
@p = ICU::Tournament::Krause.new
@t = @p.parse!(krause, :fide => true)
end
it "should have a name, city and federation" do
expect(@t.name).to eq('Las Vegas National Open')
expect(@t.city).to eq('Las Vegas')
expect(@t.fed).to eq('USA')
end
it "should have start and end dates" do
expect(@t.start).to eq('2008-06-07')
expect(@t.finish).to eq('2008-06-09')
end
it "should have a number of rounds, a type and a time control" do
expect(@t.rounds).to eq(3)
expect(@t.last_round).to eq(3)
expect(@t.type).to eq('All-Play-All')
expect(@t.time_control).to eq('60 in 2hr, 30 in 1hr, rest in 1hr')
end
it "should have an arbiter and deputies" do
expect(@t.arbiter).to eq('Hans Scmidt')
expect(@t.deputy).to eq('Gerry Graham, Herbert Scarry')
end
it "should have players and their details" do
expect(@t.players.size).to eq(3)
check_player(1, 'Gearoidin', 'Ui Laighleis', :gender => 'F', :fide_rating => 1985, :fed => 'IRL', :fide_id => 2501171, :dob => '1964-06-10', :rank => 2)
check_player(2, 'Mark', 'Orr', :gender => 'M', :fide_rating => 2258, :fed => 'IRL', :fide_id => 2500035, :dob => '1955-11-09', :rank => 1, :title => 'IM')
check_player(3, 'Viktor', 'Bologan', :gender => 'M', :fide_rating => 2663, :fed => 'MDA', :fide_id => 13900048, :dob => '1971-01-01', :rank => 3, :title => 'GM')
end
it "should have correct results for each player" do
check_results(1, 2, 1.0)
check_results(2, 2, 2.0)
check_results(3, 2, 0.0)
end
it "should have correct round dates" do
expect(@t.round_dates.join('|')).to eq('2008-06-07|2008-06-08|2008-06-09')
end
it "the parser should retain comment lines" do
comments = <<COMMENTS
062 3
072 3
082 1
0 1 2 3 4 5 6 7 8 9 0 1 2
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
COMMENTS
expect(@p.comments).to eq(comments)
end
end
context "the documentation example" do
before(:all) do
krause = <<KRAUSE
012 Fantasy Tournament
032 IRL
042 2009.09.09
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
132 09.09.09 09.09.10 09.09.11
001 1 w Mouse,Minerva 1900 USA 1234567 1928.05.15 1.0 2 2 b 0 3 w 1
001 2 m m Duck,Daffy 2200 IRL 7654321 1937.04.17 2.0 1 1 w 1 3 b 1
001 3 m g Mouse,Mickey 2600 USA 1726354 1928.05.15 0.0 3 1 b 0 2 w 0
KRAUSE
@p = ICU::Tournament::Krause.new
@t = @p.parse!(krause)
end
it "should have a name and federation" do
expect(@t.name).to eq('Fantasy Tournament')
expect(@t.fed).to eq('IRL')
end
it "should have a various dates" do
expect(@t.start).to eq('2009-09-09')
expect(@t.finish).to eq('2009-09-11')
expect(@t.round_dates.join('|')).to eq('2009-09-09|2009-09-10|2009-09-11')
end
it "should have a number of rounds" do
expect(@t.rounds).to eq(3)
end
it "should have players and their details" do
expect(@t.players.size).to eq(3)
check_player(1, 'Minerva', 'Mouse', :gender => 'F', :rating => 1900, :fed => 'USA', :fide_id => 1234567, :dob => '1928-05-15', :rank => 2)
check_player(2, 'Daffy', 'Duck', :gender => 'M', :rating => 2200, :fed => 'IRL', :fide_id => 7654321, :dob => '1937-04-17', :rank => 1, :title => 'IM')
check_player(3, 'Mickey', 'Mouse', :gender => 'M', :rating => 2600, :fed => 'USA', :fide_id => 1726354, :dob => '1928-05-15', :rank => 3, :title => 'GM')
end
it "should have correct results for each player" do
check_results(1, 2, 1.0)
check_results(2, 2, 2.0)
check_results(3, 2, 0.0)
end
it "the parser should retain comment lines" do
expect(@p.comments).to eq("0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\n")
end
end
context "the README serialisation example" do
before(:all) do
@t = ICU::Tournament.new('World Championship', '1972-07-11')
@t.add_player(ICU::Player.new('Robert J.', 'Fischer', 1))
@t.add_player(ICU::Player.new('Boris V.', 'Spassky', 2))
@t.add_result(ICU::Result.new(1, 1, 'L', :opponent => 2, :colour => 'B'))
@t.add_result(ICU::Result.new(2, 1, 'L', :opponent => 2, :colour => 'W', :rateable => false))
@t.add_result(ICU::Result.new(3, 1, 'W', :opponent => 2, :colour => 'B'))
@t.add_result(ICU::Result.new(4, 1, 'D', :opponent => 2, :colour => 'W'))
serializer = ICU::Tournament::Krause.new
@k = serializer.serialize(@t)
end
it "should produce a valid tournament" do
expect(@t.invalid).to be_falsey
end
it "should produce output that looks reasonable" do
expect(@k).to match(/Fischer,Robert J\./)
end
end
context "serialisation" do
before(:each) do
@krause = <<KRAUSE
012 Las Vegas National Open
022 Las Vegas
032 USA
042 2008-06-07
052 2008-06-09
092 All-Play-All
102 Hans Scmidt
112 Gerry Graham, Herbert Scarry
122 60 in 2hr, 30 in 1hr, rest in 1hr
013 Boys 2 3
013 Girls 1 4
132 08-06-07 08-06-08 08-06-09
001 1 w Ui Laighleis,Gearoidin 1985 IRL 2501171 1964-06-10 2.0 2 2 b 0 3 w + 4 b 1
001 2 m m Orr,Mark 2258 IRL 2500035 1955-11-09 2.5 1 1 w 1 0000 - = 3 b 1
001 3 m g Bologan,Viktor 2663 MDA 13900048 1971-01-01 0.0 4 1 b - 2 w 0
001 4 wg Cramling,Pia 2500 SWE 1700030 1963-04-23 0.5 3 0000 - = 1 w 0
KRAUSE
@p = ICU::Tournament::Krause.new
end
it "should serialize back to the original if the input is fully canonicalised" do
t = @p.parse!(@krause, :fide => true)
expect(ICU::Tournament::Krause.new.serialize(t, :fide => true)).to eq(@krause)
end
it "should serialize using the convenience method of the tournament object" do
t = @p.parse!(@krause, :fide => true)
expect(t.serialize('Krause', :fide => true)).to eq(@krause)
end
it "should serialize only if :fide option is used correctly" do
t = @p.parse!(@krause, :fide => true)
expect(t.serialize('Krause', :fide => true)).to eq(@krause)
expect(t.serialize('Krause')).not_to eq(@krause)
end
it "should not serialize correctly if mixed rating types are used" do
t = @p.parse!(@krause, :fide => true)
expect(t.serialize('Krause')).not_to eq(@krause)
end
end
context "auto-ranking" do
before(:all) do
@krause = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
001 1 w Ui Laighleis,Gearoidin 1985 IRL 2501171 1964-06-10 1.0 2 b 0 3 w 1
001 2 m m Orr,Mark 2258 IRL 2500035 1955-11-09 2.0 1 w 1 3 b 1
001 3 m g Bologan,Viktor 2663 MDA 13900048 1971-01-01 0.0 1 b 0 2 w 0
KRAUSE
@p = ICU::Tournament::Krause.new
@t = @p.parse!(@krause)
end
it "should have rankings automatically set" do
expect(@t.player(1).rank).to eq(2)
expect(@t.player(2).rank).to eq(1)
expect(@t.player(3).rank).to eq(3)
end
end
context "local or FIDE ratings and IDs" do
before(:each) do
@krause = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
001 1 w Ui Laighleis,Gearoidin 1985 IRL 2501171 1964-06-10 1.0 2 b 0 3 w 1
001 2 m m Orr,Mark 2258 IRL 1350 1955-11-09 2.0 1 w 1 3 b 1
001 3 m g Bologan,Viktor 2663 MDA 1971-01-01 0.0 1 b 0 2 w 0
KRAUSE
@p = ICU::Tournament::Krause.new
end
it "should have local ratings by default" do
@t = @p.parse(@krause)
check_player(1, 'Gearoidin', 'Ui Laighleis', :rating => 1985, :fide_rating => nil)
check_player(2, 'Mark', 'Orr', :rating => 2258, :fide_rating => nil)
check_player(3, 'Viktor', 'Bologan', :rating => 2663, :fide_rating => nil)
end
it "should have FIDE ratings if option is specified" do
@t = @p.parse(@krause, :fide => true)
check_player(1, 'Gearoidin', 'Ui Laighleis', :rating => nil, :fide_rating => 1985)
check_player(2, 'Mark', 'Orr', :rating => nil, :fide_rating => 2258)
check_player(3, 'Viktor', 'Bologan', :rating => nil, :fide_rating => 2663)
end
it "should auto-detect FIDE or ICU IDs based on size, the option has no effect" do
@t = @p.parse(@krause)
check_player(1, 'Gearoidin', 'Ui Laighleis', :id => nil, :fide_id => 2501171)
check_player(2, 'Mark', 'Orr', :id => 1350, :fide_id => nil)
@t = @p.parse(@krause, :fide => true)
check_player(1, 'Gearoidin', 'Ui Laighleis', :id => nil, :fide_id => 2501171)
check_player(2, 'Mark', 'Orr', :id => 1350, :fide_id => nil)
end
end
context "renumbering" do
before(:all) do
@krause = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
001 10 w Ui Laighleis,Gearoidin 1985 IRL 1.0 20 b 0 30 w 1
001 20 m m Orr,Mark 2258 IRL 2.0 10 w 1 30 b 1
001 30 m g Bologan,Viktor 2663 MDA 0.0 10 b 0 20 w 0
KRAUSE
@p = ICU::Tournament::Krause.new
@t = @p.parse!(@krause)
@reordered = <<REORDERED
012 Las Vegas National Open
042 2008-06-07
001 1 m m Orr,Mark 2258 IRL 2.0 1 2 w 1 3 b 1
001 2 w Ui Laighleis,Gearoidin 1985 IRL 1.0 2 1 b 0 3 w 1 #
001 3 m g Bologan,Viktor 2663 MDA 0.0 3 2 b 0 1 w 0
REORDERED
@reordered.sub!('#', '')
end
it "should serialise correctly after renumbering by rank" do
@t.renumber
expect(@p.serialize(@t)).to eq(@reordered)
end
end
context "serialisation of a manually built tournament" do
before(:all) do
@krause = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
001 1 w Ui Laighleis,Gearoidin 1985 IRL 2501171 1964-06-10 1.0 2 b 0 3 w 1 #
001 2 m Orr,Mark 2258 IRL 2500035 1955-11-09 2.0 1 w 1 3 b 1
001 3 g Bologan,Viktor 2663 MDA 13900048 1971-01-01 0.0 1 b 0 2 w 0
KRAUSE
@krause.sub!('#', '')
@p = ICU::Tournament::Krause.new
@t = ICU::Tournament.new('Las Vegas National Open', '2008-06-07')
@t.add_player(ICU::Player.new('Gearoidin', 'Ui Laighleis', 1, :rating => 1985, :id => 2501171, :dob => '1964-06-10', :fed => 'IRL', :gender => 'f'))
@t.add_player(ICU::Player.new('Mark', 'Orr', 2, :rating => 2258, :id => 2500035, :dob => '1955-11-09', :fed => 'IRL', :title => 'm'))
@t.add_player(ICU::Player.new('Viktor', 'Bologan', 3, :rating => 2663, :id => 13900048, :dob => '1971-01-01', :fed => 'MDA', :title => 'g'))
@t.add_result(ICU::Result.new(1, 1, 'L', :opponent => 2, :colour => 'B'))
@t.add_result(ICU::Result.new(2, 1, 'W', :opponent => 3, :colour => 'W'))
@t.add_result(ICU::Result.new(3, 2, 'W', :opponent => 3, :colour => 'B'))
@output = @p.serialize(@t)
end
it "should serialise" do
expect(@output).to eq(@krause)
end
end
context "customised serialisation with ICU IDs" do
before(:all) do
@k = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
001 1 w Ui Laighleis,Gearoidin 1985 IRL 3364 1964-06-10 1.0 2 2 b 0 3 w 1 #
001 2 m Orr,Mark 2258 IRL 1350 1955-11-09 2.0 1 1 w 1 3 b 1
001 3 g Svidler,Peter 2663 RUS 16790 1971-01-01 0.0 3 1 b 0 2 w 0
KRAUSE
@k.sub!('#', '')
@p = ICU::Tournament::Krause.new
@t = @p.parse(@k)
end
it "should include all data without any explict cusromisation" do
text = @t.serialize('Krause')
expect(text).to match(/001 1 w Ui Laighleis,Gearoidin 1985 IRL 3364 1964-06-10 1.0 2/)
expect(text).to match(/001 2 m Orr,Mark 2258 IRL 1350 1955-11-09 2.0 1/)
expect(text).to match(/001 3 g Svidler,Peter 2663 RUS 16790 1971-01-01 0.0 3/)
end
it "should omitt ratings and IDs if FIDE option is chosen" do
text = @t.serialize('Krause', :fide => true)
expect(text).to match(/001 1 w Ui Laighleis,Gearoidin IRL 1964-06-10 1.0 2/)
expect(text).to match(/001 2 m Orr,Mark IRL 1955-11-09 2.0 1/)
expect(text).to match(/001 3 g Svidler,Peter RUS 1971-01-01 0.0 3/)
end
it "should omitt all optional data if the :only option is an empty hash" do
text = @t.serialize('Krause', :only => [])
expect(text).to match(/001 1 Ui Laighleis,Gearoidin 1.0 /)
expect(text).to match(/001 2 Orr,Mark 2.0 /)
expect(text).to match(/001 3 Svidler,Peter 0.0 /)
end
it "should should be able to include a subset of attributes, test 1" do
text = @t.serialize('Krause', :only => [:gender, "dob", :id, "rubbish"])
expect(text).to match(/001 1 w Ui Laighleis,Gearoidin 3364 1964-06-10 1.0 /)
expect(text).to match(/001 2 Orr,Mark 1350 1955-11-09 2.0 /)
expect(text).to match(/001 3 Svidler,Peter 16790 1971-01-01 0.0 /)
end
it "should should be able to include a subset of attributes, test 2" do
text = @t.serialize('Krause', :only => [:rank, "title", :fed, "rating"])
expect(text).to match(/001 1 Ui Laighleis,Gearoidin 1985 IRL 1.0 2/)
expect(text).to match(/001 2 m Orr,Mark 2258 IRL 2.0 1/)
expect(text).to match(/001 3 g Svidler,Peter 2663 RUS 0.0 3/)
end
it "should should be able to include all attributes" do
text = @t.serialize('Krause', :only => [:gender, :title, :rating, :fed, :id, :dob, :rank])
expect(text).to match(/001 1 w Ui Laighleis,Gearoidin 1985 IRL 3364 1964-06-10 1.0 2/)
expect(text).to match(/001 2 m Orr,Mark 2258 IRL 1350 1955-11-09 2.0 1/)
expect(text).to match(/001 3 g Svidler,Peter 2663 RUS 16790 1971-01-01 0.0 3/)
end
it "the :only and :except options are logical opposites" do
expect(@t.serialize('Krause', :only => [:gender, :title, :rating])).to eq(@t.serialize('Krause', :except => [:fed, :id, "dob", :rank]))
expect(@t.serialize('Krause', :only => [:gender])).to eq(@t.serialize('Krause', :except => [:fed, :id, :dob, :rank, :title, :rating]))
expect(@t.serialize('Krause', :only => [:gender, :title, "rating", :fed, :id, :dob])).to eq(@t.serialize('Krause', :except => [:rank]))
expect(@t.serialize('Krause', :only => [:gender, :title, :rating, :fed, "id", :dob, :rank])).to eq(@t.serialize('Krause', :except => []))
expect(@t.serialize('Krause', :only => [])).to eq(@t.serialize('Krause', :except => [:gender, :title, :rating, :fed, :id, :dob, :rank]))
end
end
context "customised serialisation with FIDE IDs" do
before(:all) do
@k = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
001 1 w Ui Laighleis,Gearoidin 1985 IRL 2501171 1964-06-10 1.0 2 2 b 0 3 w 1 #
001 2 m Orr,Mark 2258 IRL 2500035 1955-11-09 2.0 1 1 w 1 3 b 1
001 3 g Svidler,Peter 2663 RUS 4102142 1971-01-01 0.0 3 1 b 0 2 w 0
KRAUSE
@k.gsub!('#', '')
@p = ICU::Tournament::Krause.new
@t = @p.parse(@k, :fide => true)
end
it "should include all data without any explict cusromisation" do
text = @t.serialize('Krause', :fide => true)
expect(text).to match(/001 1 w Ui Laighleis,Gearoidin 1985 IRL 2501171 1964-06-10 1.0 2/)
expect(text).to match(/001 2 m Orr,Mark 2258 IRL 2500035 1955-11-09 2.0 1/)
expect(text).to match(/001 3 g Svidler,Peter 2663 RUS 4102142 1971-01-01 0.0 3/)
end
it "should omitt ratings and IDs if FIDE option is not chosen" do
text = @t.serialize('Krause')
expect(text).to match(/001 1 w Ui Laighleis,Gearoidin IRL 1964-06-10 1.0 2/)
expect(text).to match(/001 2 m Orr,Mark IRL 1955-11-09 2.0 1/)
expect(text).to match(/001 3 g Svidler,Peter RUS 1971-01-01 0.0 3/)
end
it "should omitt all optional data if the :only option is an empty hash" do
text = @t.serialize('Krause', :only => [])
expect(text).to match(/001 1 Ui Laighleis,Gearoidin 1.0 /)
expect(text).to match(/001 2 Orr,Mark 2.0 /)
expect(text).to match(/001 3 Svidler,Peter 0.0 /)
end
it "should should be able to include a subset of attributes, test 1" do
text = @t.serialize('Krause', :only => [:gender, "dob", :id], :fide => true)
expect(text).to match(/001 1 w Ui Laighleis,Gearoidin 2501171 1964-06-10 1.0 /)
expect(text).to match(/001 2 Orr,Mark 2500035 1955-11-09 2.0 /)
expect(text).to match(/001 3 Svidler,Peter 4102142 1971-01-01 0.0 /)
end
it "should should be able to include a subset of attributes, test 2" do
text = @t.serialize('Krause', :only => [:rank, "title", :fed, "rating", :rubbish], :fide => true)
expect(text).to match(/001 1 Ui Laighleis,Gearoidin 1985 IRL 1.0 2/)
expect(text).to match(/001 2 m Orr,Mark 2258 IRL 2.0 1/)
expect(text).to match(/001 3 g Svidler,Peter 2663 RUS 0.0 3/)
end
it "should should be able to include all attributes" do
text = @t.serialize('Krause', :only => [:gender, :title, :rating, :fed, :id, :dob, :rank], :fide => true)
expect(text).to match(/001 1 w Ui Laighleis,Gearoidin 1985 IRL 2501171 1964-06-10 1.0 2/)
expect(text).to match(/001 2 m Orr,Mark 2258 IRL 2500035 1955-11-09 2.0 1/)
expect(text).to match(/001 3 g Svidler,Peter 2663 RUS 4102142 1971-01-01 0.0 3/)
end
end
context "errors" do
before(:each) do
@k = <<KRAUSE
012 Gonzaga Classic
022 Dublin
032 IRL
042 2008-02-21
052 2008-02-25
062 12
092 Swiss
102 Michael Germaine, [email protected]
122 120 minutes per player per game
132 08.02.21 08.02.22 08.02.23 08.02.24 08.02.25
001 1 Griffiths,Ryan Rhys IRL 2502054 1993-12-20 4.0 1 0000 - = 3 b 1 8 w 1 5 b = 7 w 1
001 2 Hotak,Marian SVK 14909677 3.5 2 3 w 0 6 b = 11 w 1 8 b 1 5 w 1
001 3 Duffy,Seamus IRL 3.0 3 2 b 1 1 w 0 4 w 1 6 b = 8 w =
001 4 Cafolla,Peter IRL 2500884 3.0 4 7 b 1 5 w = 3 b 0 11 b + 6 w =
001 5 Ferry,Edward SCO 2461587 3.0 5 10 b 1 4 b = 9 w 1 1 w = 2 b 0
001 6 Boyle,Bernard IRL 2501830 3.0 6 12 b = 2 w = 10 b 1 3 w = 4 b =
001 7 McCarthy,Tim IRL 2500710 2.5 7 4 w 0 10 w = 12 b + 9 b 1 1 b 0
001 8 Benson,Oisin P. IRL 2501821 2.0 8 0000 - = 11 w 1 1 b 0 2 w 0 3 b =
001 9 Murray,David B. IRL 2501511 2.0 9 11 b = 12 w + 5 b 0 7 w 0 10 w =
001 10 Moser,Philippe SUI 1308041 1.5 10 5 w 0 7 b = 6 w 0 0000 - = 9 b =
001 11 Barbosa,Paulo POR 1904612 1.5 11 9 w = 8 b 0 2 b 0 4 w - 0000 - +
001 12 McCabe,Darren IRL 2500760 0.5 12 6 w = 9 b - 7 w -
KRAUSE
@p = ICU::Tournament::Krause.new
end
it "the unaltered example is valid Krause" do
expect { @p.parse!(@k) }.not_to raise_error
end
it "removing the line on which the tournament name is specified should cause an error" do
expect { @p.parse!(@k.sub('012 Gonzaga Classic', '')) }.to raise_error(/name missing/)
end
it "blanking the tournament name should cause an error" do
@k.sub!('Gonzaga Classic', '')
expect { @p.parse!(@k) }.to raise_error(/name missing/)
end
it "the start cannot be later than the end date" do
expect { @p.parse!(@k.sub('2008-02-21', '2008-03-21')) }.to raise_error(/start.*after.*end/)
end
it "blanking the start date should cause an error" do
expect { @p.parse!(@k.sub('2008-02-21', '')) }.to raise_error(/start date missing/)
end
it "the first and last round dates should match the tournament start and end dates" do
expect { @p.parse!(@k.sub('08.02.21', '08.02.20')) }.to raise_error(/first round.*not match.*start/)
expect { @p.parse!(@k.sub('08.02.21', '08.02.22')) }.to raise_error(/first round.*not match.*start/)
expect { @p.parse!(@k.sub('08.02.25', '08.02.24')) }.to raise_error(/last round.*not match.*end/)
expect { @p.parse!(@k.sub('08.02.25', '08.02.26')) }.to raise_error(/last round.*not match.*end/)
end
it "the round dates should never decrease" do
expect { @p.parse!(@k.sub('08.02.24', '08.02.22')) }.to raise_error(/round 3.*after.*round 4/)
end
it "bad round dates can be ignored" do
expect { @p.parse!(@k.sub('08.02.21', '08.02.20'), :round_dates => "ignore") }.not_to raise_error
expect { @p.parse!(@k.sub('08.02.24', '08.02.22'), :round_dates => "ignore") }.not_to raise_error
end
it "creating a duplicate player number should cause an error" do
expect { @p.parse!(@k.sub(' 2 ', ' 1 ')) }.to raise_error(/player number/)
end
it "creating a duplicate rank number should not cause an error becuse the tournament will be reranked" do
t = @p.parse!(@k.sub('4.0 1', '4.0 2'))
expect(t.player(1).rank).to eq(1)
end
it "referring to a non-existant player number should cause an error" do
expect { @p.parse!(@k.sub(' 3 b 1', '33 b 1')) }.to raise_error(/opponent number/)
end
it "inconsistent colours should cause an error" do
expect { @p.parse!(@k.sub('3 b 1', '3 w 1')) }.to raise_error(/result/)
end
it "inconsistent scores should cause an error" do
expect { @p.parse!(@k.sub('3 b 1', '3 b =')) }.to raise_error(/result/)
end
it "inconsistent totals should cause an error" do
expect { @p.parse!(@k.sub('3.5', '4.0')) }.to raise_error(/total/)
end
it "invalid federations should cause an error unless an option is used" do
@k.sub!('SCO', 'XYZ')
expect { @p.parse!(@k) }.to raise_error(/federation/)
expect { @t = @p.parse!(@k, :fed => "skip") }.not_to raise_error
expect(@t.player(5).fed).to be_nil
expect(@t.player(1).fed).to eq("IRL")
expect { @t = @p.parse!(@k, :fed => "ignore") }.not_to raise_error
expect(@t.player(5).fed).to be_nil
expect(@t.player(1).fed).to be_nil
end
it "an invalid DOB is silently ignored" do
expect { @t = @p.parse!(@k.sub(/1993-12-20/, '1993 ')) }.not_to raise_error
expect(@t.player(1).dob).to be_nil
end
it "removing any player that somebody else has played should cause an error" do
expect { @p.parse!(@k.sub(/^001 12.*$/, '')) }.to raise_error(/opponent/)
end
end
context "encoding" do
before(:all) do
@utf8 = <<KRAUSE
012 Läs Végas National Opeñ
042 2008-06-07
001 1 w Uì Laighlèis,Gearoìdin 1.0 2 b 0 3 w 1
001 2 m m Örr,Mârk 2.0 1 w 1 3 b 1
001 3 m g Bologan,Viktor 0.0 1 b 0 2 w 0
KRAUSE
@p = ICU::Tournament::Krause.new
end
it "should handle UTF-8" do
@t = @p.parse!(@utf8)
check_player(1, 'Gearoìdin', 'Uì Laighlèis')
check_player(2, 'Mârk', 'Örr')
check_player(3, 'Viktor', 'Bologan')
expect(@t.name).to eq("Läs Végas National Opeñ")
end
it "should handle Latin-1" do
latin1 = @utf8.encode("ISO-8859-1")
@t = @p.parse!(latin1)
check_player(1, 'Gearoìdin', 'Uì Laighlèis')
check_player(2, 'Mârk', 'Örr')
check_player(3, 'Viktor', 'Bologan')
expect(@t.name).to eq("Läs Végas National Opeñ")
end
end
context "preserving original names" do
before(:all) do
@k = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
001 1 w ui laighleis,GEAROIDIN 1.0 2 b 0 3 w 1
001 2 m m ORR, mark 2.0 1 w 1 3 b 1
001 3 m g BOLOGAN,VIKTOR 0.0 1 b 0 2 w 0
KRAUSE
@p = ICU::Tournament::Krause.new
end
it "should canonicalise names but also preserve originals" do
@t = @p.parse!(@k)
check_player(1, 'Gearoidin', 'Ui Laighleis')
check_player(2, 'Mark', 'Orr')
check_player(3, 'Viktor', 'Bologan')
expect(@t.player(1).original_name).to eq("ui laighleis, GEAROIDIN")
expect(@t.player(2).original_name).to eq("ORR, mark")
expect(@t.player(3).original_name).to eq("BOLOGAN, VIKTOR")
end
end
context "parsing files" do
before(:each) do
@p = ICU::Tournament::Krause.new
@s = File.dirname(__FILE__) + '/samples/krause'
end
it "should error on a non-existant valid file" do
file = "#{@s}/not_there.tab"
expect { @p.parse_file!(file) }.to raise_error
t = @p.parse_file(file)
expect(t).to be_nil
expect(@p.error).to match(/no such file/i)
end
it "should error on an invalid file" do
file = "#{@s}/invalid.tab"
expect { @p.parse_file!(file) }.to raise_error
t = @p.parse_file(file)
expect(t).to be_nil
expect(@p.error).to match(/tournament name missing/i)
end
it "should parse a valid file" do
file = "#{@s}/valid.tab"
expect { @p.parse_file!(file) }.not_to raise_error
t = @p.parse_file(file)
expect(t).to be_an_instance_of(ICU::Tournament)
expect(t.players.size).to eq(12)
end
it "should parse a file with UTF-8 encoding" do
file = "#{@s}/utf-8.tab"
expect { @t = @p.parse_file!(file) }.not_to raise_error
check_player(1, 'Gearoìdin', 'Uì Laighlèis')
check_player(2, 'Mârk', 'Örr')
check_player(3, 'Viktor', 'Bologan')
expect(@t.name).to eq("Läs Végas National Opeñ")
end
it "should parse a file with Latin-1 encoding" do
file = "#{@s}/latin-1.tab"
expect { @t = @p.parse_file!(file) }.not_to raise_error
check_player(1, 'Gearoìdin', 'Uì Laighlèis')
check_player(2, 'Mârk', 'Örr')
check_player(3, 'Viktor', 'Bologan')
expect(@t.name).to eq("Läs Végas National Opeñ")
end
it "should parse a large file with total scores as much as 10.0" do
file = "#{@s}/armstrong_2011.tab"
expect { @t = @p.parse_file!(file) }.not_to raise_error
end
end
context "automatic repairing of totals" do
before(:each) do
@p = ICU::Tournament::Krause.new
end
it "cannot repair mismatched totals if there are no byes" do
@k = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
001 1 Ui Laighleis,Gearoidin 0.5 2 b 0 2 w 0
001 2 Or,Mark 2.0 1 w 1 1 b 1
KRAUSE
expect { @p.parse!(@k) }.to raise_error(/total/)
end
it "cannot repair mismatched totals if totals are underestimated" do
@k = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
001 1 Ui Laighleis,Gearoidin 0.0 2 b 0 0000 - -
001 2 Orr,Mark 1.5 1 w 1 0000 - +
KRAUSE
expect { @p.parse!(@k) }.to raise_error(/total/)
end
it "cannot repair overestimated totals if there are not enough byes" do
@k = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
001 1 Ui Laighleis,Gearoidin 1.5 2 b 0 0000 - -
001 2 Orr,Mark 2.0 1 w 1 0000 - +
KRAUSE
expect { @p.parse!(@k) }.to raise_error(/total/)
end
it "can repair overestimated totals if there are enough byes" do
@k = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
001 1 Ui Laighleis,Gearoidin 1.0 2 b 0 0000 - -
001 2 ORR,Mark 2.0 1 w 1 0000 - +
KRAUSE
@t = @p.parse!(@k)
expect(@t).not_to be_nil
check_results(1, 2, 1.0)
expect(@t.player(1).find_result(2).score).to eq('W')
end
it "extreme example" do
@k = <<KRAUSE
012 Las Vegas National Open
042 2008-06-07
001 1 Ui Laighleis,Gearoidin 2.0 2 b 0 0000 - - 0000 - =
001 2 Orr,Mark 2.5 1 w 1 0000 - +
001 3 Brady,Stephen 1.0 0000 - - 4 b 0 0000 - =
001 4 Knox,Angela 2.5 0000 - - 3 w 1 0000 - -
KRAUSE
@t = @p.parse!(@k)
expect(@t).not_to be_nil
expect(@t.player(1).results.map(&:score).join('')).to eq('LWW')
expect(@t.player(2).results.map(&:score).join('')).to eq('WWD')
expect(@t.player(3).results.map(&:score).join('')).to eq('DLD')
expect(@t.player(4).results.map(&:score).join('')).to eq('WWD')
end
it "should work on the documentation example" do
@k = <<KRAUSE
012 Mismatched Totals
042 2011-03-04
001 1 Mouse,Minerva 1.0 2 2 b 0 0000 - =
001 2 Mouse,Mickey 1.5 1 1 w 1
KRAUSE
@t = @p.parse!(@k)
output = <<KRAUSE
012 Mismatched Totals
042 2011-03-04
001 1 Mouse,Minerva 1.0 2 2 b 0 0000 - +
001 2 Mouse,Mickey 1.5 1 1 w 1 0000 - =
KRAUSE
expect(@t.serialize('Krause')).to eq(output)
end
end
context "parsing variations on strict Krause" do
before(:each) do
@p = ICU::Tournament::Krause.new
@s = File.dirname(__FILE__) + '/samples/krause'
end
it "should handle Bunratty Masters 2011" do
file = "#{@s}/bunratty_masters_2011.tab"
@t = @p.parse_file(file, :fed => :skip, :fide => true)
expect(@t).not_to be_nil
expect(@t.start).to eq("2011-02-25")
expect(@t.finish).to eq("2011-02-27")
check_player(1, 'Nigel', 'Short', :gender => 'M', :fide_rating => 2658, :fed => 'ENG', :rating => nil, :rank => 5, :title => 'GM')
check_results(1, 6, 4.0)
check_player(16, 'Jonathan', "O'Connor", :gender => 'M', :fide_rating => 2111, :fed => nil, :rating => nil, :rank => 25, :title => nil)
check_results(16, 6, 2.5)
expect(@t.player(16).results.map(&:score).join('')).to eq('DWLDDL')
check_player(24, 'David', 'Murray', :gender => 'M', :fide_rating => 2023, :fed => nil, :rating => nil, :rank => 34, :title => nil)
check_results(24, 2, 0.5)
expect(@t.player(24).results.map(&:score).join('')).to eq('LD')
check_player(26, 'Alexandra', 'Wilson', :gender => 'F', :fide_rating => 2020, :fed => 'ENG', :rating => nil, :rank => 29, :title => 'WFM')
check_results(26, 6, 2.0)
end
it "should handle Bunratty Major 2011" do
file = "#{@s}/bunratty_major_2011.tab"
@t = @p.parse_file(file, :fed => :ignore)
expect(@t).not_to be_nil
expect(@t.start).to eq("2011-02-25")
expect(@t.finish).to eq("2011-02-27")
check_player(1, 'Dan', 'Clancy', :gender => 'M', :fide_rating => nil, :fed => nil, :id => 204, :rating => nil, :rank => 12)
check_results(1, 6, 4)
check_player(10, 'Phillip', 'Foenander', :gender => 'M', :fide_rating => nil, :fed => nil, :id => 7168, :rating => nil, :rank => 18)
check_results(10, 6, 3.5)
check_player(40, 'Ron', 'Cummins', :gender => 'M', :fide_rating => nil, :fed => nil, :id => 4610, :rating => nil, :rank => 56)
check_results(40, 1, 0.0)
end
it "should handle bunratty_minor_2011.tab" do
file = "#{@s}/bunratty_minor_2011.tab"
expect { @p.parse_file!(file, :fed => :ignore) }.not_to raise_error
end
it "should handle Bunratty Challengers 2011" do
file = "#{@s}/bunratty_challengers_2011.tab"
expect { @p.parse_file!(file, :fed => :ignore) }.not_to raise_error
end
it "should handle Irish Intermediate Championships 2011" do
file = "#{@s}/irish_intermediate_champs_2011.tab"
expect { @p.parse_file!(file) }.not_to raise_error
end
it "should handle Irish Junior Championships 2011" do
file = "#{@s}/irish_junior_champs_2011.tab"
expect { @p.parse_file!(file) }.not_to raise_error
end
it "should handle Cork Major 2018 (Swiss Master format)" do
file = "#{@s}/cork_major_2018_swissmaster.tab"
@t = @p.parse_file(file, :fed => :ignore)
check_results(1, 6, 3.5)
end
it "should handle a file with a BOM" do
file = "#{@s}/armstrong_2012_with_bom.tab"
expect { @p.parse_file!(file) }.not_to raise_error
end
end
end
end
end
| 49.478155 | 179 | 0.495193 |
0163f56c42e946df1adf6e8394b2a5f06365b1dd | 98 | FactoryGirl.define do
factory :requests_refund, :class => 'Requests::Refund' do
end
end
| 14 | 59 | 0.693878 |
21d88a1d99aa9b9dea14a50dd5dee955b1774fa9 | 38,093 | #
# Rest API Request Tests - Services specs
#
# - Create service /api/services/ action "create"
#
# - Edit service /api/services/:id action "edit"
# - Edit service via PUT /api/services/:id PUT
# - Edit service via PATCH /api/services/:id PATCH
# - Edit multiple services /api/services action "edit"
#
# - Delete service /api/services/:id DELETE
# - Delete multiple services /api/services action "delete"
#
# - Retire service now /api/services/:id action "retire"
# - Retire service future /api/services/:id action "retire"
# - Retire multiple services /api/services action "retire"
#
# - Reconfigure service /api/services/:id action "reconfigure"
#
# - Query vms subcollection /api/services/:id/vms
# /api/services/:id?expand=vms
# with subcollection
# virtual attribute: /api/services/:id?expand=vms&attributes=vms.cpu_total_cores
#
describe "Services API" do
let(:svc) { FactoryGirl.create(:service, :name => "svc", :description => "svc description") }
let(:svc1) { FactoryGirl.create(:service, :name => "svc1", :description => "svc1 description") }
let(:svc2) { FactoryGirl.create(:service, :name => "svc2", :description => "svc2 description") }
let(:svc_orchestration) { FactoryGirl.create(:service_orchestration) }
let(:orchestration_template) { FactoryGirl.create(:orchestration_template) }
let(:ems) { FactoryGirl.create(:ext_management_system) }
describe "Services create" do
it "rejects requests without appropriate role" do
api_basic_authorize
run_post(services_url, gen_request(:create, "name" => "svc_new_1"))
expect(response).to have_http_status(:forbidden)
end
it "supports creates of single resource" do
api_basic_authorize collection_action_identifier(:services, :create)
expect do
run_post(services_url, gen_request(:create, "name" => "svc_new_1"))
end.to change(Service, :count).by(1)
expect(response).to have_http_status(:ok)
expect_results_to_match_hash("results", [{"name" => "svc_new_1"}])
end
it "supports creates of multiple resources" do
api_basic_authorize collection_action_identifier(:services, :create)
expect do
run_post(services_url, gen_request(:create,
[{"name" => "svc_new_1"},
{"name" => "svc_new_2"}]))
end.to change(Service, :count).by(2)
expect(response).to have_http_status(:ok)
expect_results_to_match_hash("results",
[{"name" => "svc_new_1"},
{"name" => "svc_new_2"}])
end
it 'supports creation of a single resource with href references' do
api_basic_authorize collection_action_identifier(:services, :create)
request = {
'action' => 'create',
'resource' => {
'type' => 'ServiceOrchestration',
'name' => 'svc_new',
'parent_service' => { 'href' => services_url(svc1.id)},
'orchestration_template' => { 'href' => orchestration_templates_url(orchestration_template.id) },
'orchestration_manager' => { 'href' => providers_url(ems.id) }
}
}
expect do
run_post(services_url, request)
end.to change(Service, :count).by(1)
expect(response).to have_http_status(:ok)
expect_results_to_match_hash("results", [{"name" => "svc_new"}])
end
it 'supports creation of a single resource with id references' do
api_basic_authorize collection_action_identifier(:services, :create)
request = {
'action' => 'create',
'resource' => {
'type' => 'ServiceOrchestration',
'name' => 'svc_new',
'parent_service' => { 'id' => svc1.id},
'orchestration_template' => { 'id' => orchestration_template.id },
'orchestration_manager' => { 'id' => ems.id }
}
}
expect do
run_post(services_url, request)
end.to change(Service, :count).by(1)
expect(response).to have_http_status(:ok)
expect_results_to_match_hash("results", [{"name" => "svc_new"}])
end
end
describe "Services edit" do
it "rejects requests without appropriate role" do
api_basic_authorize
run_post(services_url(svc.id), gen_request(:edit, "name" => "sample service"))
expect(response).to have_http_status(:forbidden)
end
it "supports edits of single resource" do
api_basic_authorize collection_action_identifier(:services, :edit)
run_post(services_url(svc.id), gen_request(:edit, "name" => "updated svc1"))
expect_single_resource_query("id" => svc.compressed_id, "href" => services_url(svc.id), "name" => "updated svc1")
expect(svc.reload.name).to eq("updated svc1")
end
it 'accepts reference signature hrefs' do
api_basic_authorize collection_action_identifier(:services, :edit)
resource = {
'action' => 'edit',
'resource' => {
'parent_service' => { 'href' => services_url(svc1.id) },
'orchestration_template' => { 'href' => orchestration_templates_url(orchestration_template.id) },
'orchestration_manager' => { 'href' => providers_url(ems.id) }
}
}
run_post(services_url(svc_orchestration.id), resource)
expected = {
'id' => svc_orchestration.compressed_id,
'ancestry' => svc1.id.to_s
}
expect(response.parsed_body).to include(expected)
expect(response).to have_http_status(:ok)
expect(svc_orchestration.reload.parent).to eq(svc1)
expect(svc_orchestration.orchestration_template).to eq(orchestration_template)
expect(svc_orchestration.orchestration_manager).to eq(ems)
end
it 'accepts reference signature ids' do
api_basic_authorize collection_action_identifier(:services, :edit)
resource = {
'action' => 'edit',
'resource' => {
'parent_service' => { 'id' => svc1.id },
'orchestration_template' => { 'id' => orchestration_template.id },
'orchestration_manager' => { 'id' => ems.id }
}
}
run_post(services_url(svc_orchestration.id), resource)
expected = {
'id' => svc_orchestration.compressed_id,
'ancestry' => svc1.id.to_s
}
expect(response.parsed_body).to include(expected)
expect(response).to have_http_status(:ok)
expect(svc_orchestration.reload.parent).to eq(svc1)
expect(svc_orchestration.orchestration_template).to eq(orchestration_template)
expect(svc_orchestration.orchestration_manager).to eq(ems)
end
it "supports edits of single resource via PUT" do
api_basic_authorize collection_action_identifier(:services, :edit)
run_put(services_url(svc.id), "name" => "updated svc1")
expect_single_resource_query("id" => svc.compressed_id, "href" => services_url(svc.id), "name" => "updated svc1")
expect(svc.reload.name).to eq("updated svc1")
end
it "supports edits of single resource via PATCH" do
api_basic_authorize collection_action_identifier(:services, :edit)
run_patch(services_url(svc.id), [{"action" => "edit", "path" => "name", "value" => "updated svc1"},
{"action" => "remove", "path" => "description"},
{"action" => "add", "path" => "display", "value" => true}])
expect_single_resource_query("id" => svc.compressed_id, "name" => "updated svc1", "display" => true)
expect(svc.reload.name).to eq("updated svc1")
expect(svc.description).to be_nil
expect(svc.display).to be_truthy
end
it "supports edits of multiple resources" do
api_basic_authorize collection_action_identifier(:services, :edit)
run_post(services_url, gen_request(:edit,
[{"href" => services_url(svc1.id), "name" => "updated svc1"},
{"href" => services_url(svc2.id), "name" => "updated svc2"}]))
expect(response).to have_http_status(:ok)
expect_results_to_match_hash("results",
[{"id" => svc1.compressed_id, "name" => "updated svc1"},
{"id" => svc2.compressed_id, "name" => "updated svc2"}])
expect(svc1.reload.name).to eq("updated svc1")
expect(svc2.reload.name).to eq("updated svc2")
end
end
describe "Services delete" do
it "rejects POST delete requests without appropriate role" do
api_basic_authorize
run_post(services_url, gen_request(:delete, "href" => services_url(100)))
expect(response).to have_http_status(:forbidden)
end
it "rejects DELETE requests without appropriate role" do
api_basic_authorize
run_delete(services_url(100))
expect(response).to have_http_status(:forbidden)
end
it "rejects requests for invalid resources" do
api_basic_authorize collection_action_identifier(:services, :delete)
run_delete(services_url(999_999))
expect(response).to have_http_status(:not_found)
end
it "supports single resource deletes" do
api_basic_authorize collection_action_identifier(:services, :delete)
run_delete(services_url(svc.id))
expect(response).to have_http_status(:no_content)
expect { svc.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
it "can be deleted via POST with an appropriate role" do
service = FactoryGirl.create(:service)
api_basic_authorize(action_identifier(:services, :delete))
expect do
run_post(services_url(service.id), :action => "delete")
end.to change(Service, :count).by(-1)
expected = {
"success" => true,
"message" => "services id: #{service.id} deleting",
"href" => a_string_matching(services_url(service.id))
}
expect(response.parsed_body).to include(expected)
expect(response).to have_http_status(:ok)
end
it "won't delete a service via POST without an appropriate role" do
service = FactoryGirl.create(:service)
api_basic_authorize
expect do
run_post(services_url(service.id), :action => "delete")
end.not_to change(Service, :count)
expect(response).to have_http_status(:forbidden)
end
it "supports multiple resource deletes" do
api_basic_authorize collection_action_identifier(:services, :delete)
run_post(services_url, gen_request(:delete,
[{"href" => services_url(svc1.id)},
{"href" => services_url(svc2.id)}]))
expect_multiple_action_result(2)
expect_result_resources_to_include_hrefs("results",
[services_url(svc1.id), services_url(svc2.id)])
expect { svc1.reload }.to raise_error(ActiveRecord::RecordNotFound)
expect { svc2.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
describe "Services retirement" do
def format_retirement_date(time)
time.in_time_zone('UTC').strftime("%Y-%m-%dT%H:%M:%SZ")
end
it "rejects requests without appropriate role" do
api_basic_authorize
run_post(services_url(100), gen_request(:retire))
expect(response).to have_http_status(:forbidden)
end
it "rejects multiple requests without appropriate role" do
api_basic_authorize
run_post(services_url, gen_request(:retire, [{"href" => services_url(1)}, {"href" => services_url(2)}]))
expect(response).to have_http_status(:forbidden)
end
it "supports single service retirement now" do
api_basic_authorize collection_action_identifier(:services, :retire)
expect(MiqEvent).to receive(:raise_evm_event).once
run_post(services_url(svc.id), gen_request(:retire))
expect_single_resource_query("id" => svc.compressed_id, "href" => services_url(svc.id))
end
it "supports single service retirement in future" do
api_basic_authorize collection_action_identifier(:services, :retire)
ret_date = format_retirement_date(Time.now + 5.days)
run_post(services_url(svc.id), gen_request(:retire, "date" => ret_date, "warn" => 2))
expect_single_resource_query("id" => svc.compressed_id, "retires_on" => ret_date, "retirement_warn" => 2)
expect(format_retirement_date(svc.reload.retires_on)).to eq(ret_date)
expect(svc.retirement_warn).to eq(2)
end
it "supports multiple service retirement now" do
api_basic_authorize collection_action_identifier(:services, :retire)
expect(MiqEvent).to receive(:raise_evm_event).twice
run_post(services_url, gen_request(:retire,
[{"href" => services_url(svc1.id)},
{"href" => services_url(svc2.id)}]))
expect_results_to_match_hash("results", [{"id" => svc1.compressed_id}, {"id" => svc2.compressed_id}])
end
it "supports multiple service retirement in future" do
api_basic_authorize collection_action_identifier(:services, :retire)
ret_date = format_retirement_date(Time.now + 2.days)
run_post(services_url, gen_request(:retire,
[{"href" => services_url(svc1.id), "date" => ret_date, "warn" => 3},
{"href" => services_url(svc2.id), "date" => ret_date, "warn" => 5}]))
expect_results_to_match_hash("results",
[{"id" => svc1.compressed_id, "retires_on" => ret_date, "retirement_warn" => 3},
{"id" => svc2.compressed_id, "retires_on" => ret_date, "retirement_warn" => 5}])
expect(format_retirement_date(svc1.reload.retires_on)).to eq(ret_date)
expect(svc1.retirement_warn).to eq(3)
expect(format_retirement_date(svc2.reload.retires_on)).to eq(ret_date)
expect(svc2.retirement_warn).to eq(5)
end
end
describe "Service reconfiguration" do
let(:dialog1) { FactoryGirl.create(:dialog_with_tab_and_group_and_field) }
let(:st1) { FactoryGirl.create(:service_template, :name => "template1") }
let(:ra1) do
FactoryGirl.create(:resource_action, :action => "Reconfigure", :dialog => dialog1,
:ae_namespace => "namespace", :ae_class => "class", :ae_instance => "instance")
end
it "rejects requests without appropriate role" do
api_basic_authorize
run_post(services_url(100), gen_request(:reconfigure))
expect(response).to have_http_status(:forbidden)
end
it "does not return reconfigure action for non-reconfigurable services" do
api_basic_authorize(action_identifier(:services, :read, :resource_actions, :get),
action_identifier(:services, :retire),
action_identifier(:services, :reconfigure))
run_get services_url(svc1.id)
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to declare_actions("retire")
end
it "returns reconfigure action for reconfigurable services" do
api_basic_authorize(action_identifier(:services, :read, :resource_actions, :get),
action_identifier(:services, :retire),
action_identifier(:services, :reconfigure))
st1.resource_actions = [ra1]
svc1.service_template_id = st1.id
svc1.save
run_get services_url(svc1.id)
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to declare_actions("retire", "reconfigure")
end
it "accepts action when service is reconfigurable" do
api_basic_authorize
update_user_role(@role, action_identifier(:services, :reconfigure))
st1.resource_actions = [ra1]
svc1.service_template_id = st1.id
svc1.save
run_post(services_url(svc1.id), gen_request(:reconfigure, "text1" => "updated_text"))
expect_single_action_result(:success => true, :message => /reconfiguring/i, :href => services_url(svc1.id))
end
end
describe "Services" do
let(:hw1) { FactoryGirl.build(:hardware, :cpu_total_cores => 2) }
let(:vm1) { FactoryGirl.create(:vm_vmware, :hardware => hw1) }
let(:hw2) { FactoryGirl.build(:hardware, :cpu_total_cores => 4) }
let(:vm2) { FactoryGirl.create(:vm_vmware, :hardware => hw2) }
before do
api_basic_authorize(action_identifier(:services, :read, :resource_actions, :get))
svc1 << vm1
svc1 << vm2
svc1.save
@svc1_vm_list = ["#{services_url(svc1.id)}/vms/#{vm1.id}", "#{services_url(svc1.id)}/vms/#{vm2.id}"]
end
def expect_svc_with_vms
expect_single_resource_query("href" => services_url(svc1.id))
expect_result_resources_to_include_hrefs("vms", @svc1_vm_list)
end
it "can query vms as subcollection" do
run_get "#{services_url(svc1.id)}/vms"
expect_query_result(:vms, 2, 2)
expect_result_resources_to_include_hrefs("resources", @svc1_vm_list)
end
it "supports expansion of virtual attributes" do
run_get services_url, :expand => "resources", :attributes => "power_states"
expected = {
"resources" => [
a_hash_including("power_states" => svc1.power_states)
]
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to include(expected)
end
it "can query vms as subcollection via expand" do
run_get services_url(svc1.id), :expand => "vms"
expect_svc_with_vms
end
it "can query vms as subcollection via expand with additional virtual attributes" do
run_get services_url(svc1.id), :expand => "vms", :attributes => "vms.cpu_total_cores"
expect_svc_with_vms
expect_results_to_match_hash("vms", [{"id" => vm1.compressed_id, "cpu_total_cores" => 2},
{"id" => vm2.compressed_id, "cpu_total_cores" => 4}])
end
it "can query vms as subcollection via decorators with additional decorators" do
run_get services_url(svc1.id), :expand => "vms", :attributes => "", :decorators => "vms.supports_console?"
expect_svc_with_vms
expect_results_to_match_hash("vms", [{"id" => vm1.compressed_id, "supports_console?" => true},
{"id" => vm2.compressed_id, "supports_console?" => true}])
end
it "cannot query vms via both virtual attribute and subcollection" do
run_get services_url(svc1.id), :expand => "vms", :attributes => "vms"
expect_bad_request("Cannot expand subcollection vms by name and virtual attribute")
end
end
describe "Power Operations" do
describe "start" do
it "will start a service for a user with appropriate role" do
service = FactoryGirl.create(:service)
api_basic_authorize(action_identifier(:services, :start))
run_post(services_url(service.id), :action => "start")
expected = {
"href" => a_string_matching(services_url(service.id)),
"success" => true,
"message" => a_string_matching("starting")
}
expect(response.parsed_body).to include(expected)
expect(response).to have_http_status(:ok)
end
it "can start multiple services for a user with appropriate role" do
service_1, service_2 = FactoryGirl.create_list(:service, 2)
api_basic_authorize(collection_action_identifier(:services, :start))
run_post(services_url, :action => "start", :resources => [{:id => service_1.id}, {:id => service_2.id}])
expected = {
"results" => a_collection_containing_exactly(
a_hash_including("success" => true,
"message" => a_string_matching("starting"),
"task_id" => anything,
"task_href" => anything,
"href" => a_string_matching(services_url(service_1.id))),
a_hash_including("success" => true,
"message" => a_string_matching("starting"),
"task_id" => anything,
"task_href" => anything,
"href" => a_string_matching(services_url(service_2.id))),
)
}
expect(response.parsed_body).to include(expected)
expect(response).to have_http_status(:ok)
end
it "will not start a service for a user without an appropriate role" do
service = FactoryGirl.create(:service)
api_basic_authorize
run_post(services_url(service.id), :action => "start")
expect(response).to have_http_status(:forbidden)
end
end
describe "stop" do
it "will stop a service for a user with appropriate role" do
service = FactoryGirl.create(:service)
api_basic_authorize(action_identifier(:services, :stop))
run_post(services_url(service.id), :action => "stop")
expected = {
"href" => a_string_matching(services_url(service.id)),
"success" => true,
"message" => a_string_matching("stopping")
}
expect(response.parsed_body).to include(expected)
expect(response).to have_http_status(:ok)
end
it "can stop multiple services for a user with appropriate role" do
service_1, service_2 = FactoryGirl.create_list(:service, 2)
api_basic_authorize(collection_action_identifier(:services, :stop))
run_post(services_url, :action => "stop", :resources => [{:id => service_1.id}, {:id => service_2.id}])
expected = {
"results" => a_collection_containing_exactly(
a_hash_including("success" => true,
"message" => a_string_matching("stopping"),
"task_id" => anything,
"task_href" => anything,
"href" => a_string_matching(services_url(service_1.id))),
a_hash_including("success" => true,
"message" => a_string_matching("stopping"),
"task_id" => anything,
"task_href" => anything,
"href" => a_string_matching(services_url(service_2.id))),
)
}
expect(response.parsed_body).to include(expected)
expect(response).to have_http_status(:ok)
end
it "will not stop a service for a user without an appropriate role" do
service = FactoryGirl.create(:service)
api_basic_authorize
run_post(services_url(service.id), :action => "stop")
expect(response).to have_http_status(:forbidden)
end
end
describe "suspend" do
it "will suspend a service for a user with appropriate role" do
service = FactoryGirl.create(:service)
api_basic_authorize(action_identifier(:services, :suspend))
run_post(services_url(service.id), :action => "suspend")
expected = {
"href" => a_string_matching(services_url(service.id)),
"success" => true,
"message" => a_string_matching("suspending")
}
expect(response.parsed_body).to include(expected)
expect(response).to have_http_status(:ok)
end
it "can suspend multiple services for a user with appropriate role" do
service_1, service_2 = FactoryGirl.create_list(:service, 2)
api_basic_authorize(collection_action_identifier(:services, :suspend))
run_post(services_url, :action => "suspend", :resources => [{:id => service_1.id}, {:id => service_2.id}])
expected = {
"results" => a_collection_containing_exactly(
a_hash_including("success" => true,
"message" => a_string_matching("suspending"),
"task_id" => anything,
"task_href" => anything,
"href" => a_string_matching(services_url(service_1.id))),
a_hash_including("success" => true,
"message" => a_string_matching("suspending"),
"task_id" => anything,
"task_href" => anything,
"href" => a_string_matching(services_url(service_2.id))),
)
}
expect(response.parsed_body).to include(expected)
expect(response).to have_http_status(:ok)
end
it "will not suspend a service for a user without an appropriate role" do
service = FactoryGirl.create(:service)
api_basic_authorize
run_post(services_url(service.id), :action => "suspend")
expect(response).to have_http_status(:forbidden)
end
end
end
describe 'Orchestration Stack subcollection' do
let(:os) { FactoryGirl.create(:orchestration_stack) }
before do
svc.add_resource!(os, :name => ResourceAction::PROVISION)
end
it 'can query orchestration stacks as a subcollection' do
api_basic_authorize subcollection_action_identifier(:services, :orchestration_stacks, :read, :get)
run_get("#{services_url(svc.id)}/orchestration_stacks", :expand => 'resources')
expected = {
'resources' => [
a_hash_including('id' => os.compressed_id)
]
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to include(expected)
end
it 'can query a specific orchestration stack' do
api_basic_authorize subcollection_action_identifier(:services, :orchestration_stacks, :read, :get)
run_get("#{services_url(svc.id)}/orchestration_stacks/#{os.id}")
expected = {'id' => os.compressed_id}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to include(expected)
end
it 'can query a specific orchestration stack asking for stdout' do
api_basic_authorize subcollection_action_identifier(:services, :orchestration_stacks, :read, :get)
allow_any_instance_of(OrchestrationStack).to receive(:stdout).with(nil).and_return("default text stdout")
run_get("#{services_url(svc.id)}/orchestration_stacks/#{os.id}", :attributes => "stdout")
expected = {
'id' => os.compressed_id,
'stdout' => "default text stdout"
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to include(expected)
end
it 'can query a specific orchestration stack asking for stdout in alternate format' do
api_basic_authorize subcollection_action_identifier(:services, :orchestration_stacks, :read, :get)
allow_any_instance_of(OrchestrationStack).to receive(:stdout).with("json").and_return("json stdout")
run_get("#{services_url(svc.id)}/orchestration_stacks/#{os.id}", :attributes => "stdout", :format_attributes => "stdout=json")
expected = {
'id' => os.compressed_id,
'stdout' => "json stdout"
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to include(expected)
end
it 'will not return orchestration stacks without an appropriate role' do
api_basic_authorize
run_get("#{services_url(svc.id)}/orchestration_stacks")
expect(response).to have_http_status(:forbidden)
end
end
describe 'add_resource' do
let(:vm1) { FactoryGirl.create(:vm_vmware) }
let(:vm2) { FactoryGirl.create(:vm_vmware) }
it 'can add vm to services by href with an appropriate role' do
api_basic_authorize(collection_action_identifier(:services, :add_resource))
request = {
'action' => 'add_resource',
'resources' => [
{ 'href' => services_url(svc.id), 'resource' => {'href' => vms_url(vm1.id)} },
{ 'href' => services_url(svc1.id), 'resource' => {'href' => vms_url(vm2.id)} }
]
}
run_post(services_url, request)
expected = {
'results' => [
{ 'success' => true, 'message' => "Assigned resource vms id:#{vm1.id} to Service id:#{svc.id} name:'#{svc.name}'"},
{ 'success' => true, 'message' => "Assigned resource vms id:#{vm2.id} to Service id:#{svc1.id} name:'#{svc1.name}'"}
]
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
expect(svc.reload.vms).to eq([vm1])
expect(svc1.reload.vms).to eq([vm2])
end
it 'returns individual success and failures' do
user = FactoryGirl.create(:user)
api_basic_authorize(collection_action_identifier(:services, :add_resource))
request = {
'action' => 'add_resource',
'resources' => [
{ 'href' => services_url(svc.id), 'resource' => {'href' => vms_url(vm1.id)} },
{ 'href' => services_url(svc1.id), 'resource' => {'href' => users_url(user.id)} }
]
}
run_post(services_url, request)
expected = {
'results' => [
{ 'success' => true, 'message' => "Assigned resource vms id:#{vm1.id} to Service id:#{svc.id} name:'#{svc.name}'"},
{ 'success' => false, 'message' => "Cannot assign users to Service id:#{svc1.id} name:'#{svc1.name}'"}
]
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
expect(svc.reload.vms).to eq([vm1])
end
it 'requires a valid resource' do
api_basic_authorize(collection_action_identifier(:services, :add_resource))
request = {
'action' => 'add_resource',
'resource' => { 'resource' => { 'href' => '1' } }
}
run_post(services_url(svc.id), request)
expected = { 'success' => false, 'message' => "Invalid resource href specified 1"}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
end
it 'requires the resource to respond to add_to_service' do
user = FactoryGirl.create(:user)
api_basic_authorize(collection_action_identifier(:services, :add_resource))
request = {
'action' => 'add_resource',
'resource' => { 'resource' => { 'href' => users_url(user.id) } }
}
run_post(services_url(svc.id), request)
expected = { 'success' => false, 'message' => "Cannot assign users to Service id:#{svc.id} name:'#{svc.name}'"}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
end
it 'requires a resource reference' do
api_basic_authorize(collection_action_identifier(:services, :add_resource))
request = {
'action' => 'add_resource',
'resource' => { 'resource' => {} }
}
run_post(services_url(svc.id), request)
expected = { 'success' => false, 'message' => "Must specify a resource reference"}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
end
it 'can add a vm to a resource with appropriate role' do
api_basic_authorize(collection_action_identifier(:services, :add_resource))
request = {
'action' => 'add_resource',
'resource' => { 'resource' => {'href' => vms_url(vm1.id)} }
}
run_post(services_url(svc.id), request)
expected = { 'success' => true, 'message' => "Assigned resource vms id:#{vm1.id} to Service id:#{svc.id} name:'#{svc.name}'"}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
expect(svc.reload.vms).to eq([vm1])
end
it 'cannot add multiple vms to multiple services by href without an appropriate role' do
api_basic_authorize
run_post(services_url, 'action' => 'add_resource')
expect(response).to have_http_status(:forbidden)
end
end
describe 'remove_resource' do
let(:vm1) { FactoryGirl.create(:vm_vmware) }
let(:vm2) { FactoryGirl.create(:vm_vmware) }
before do
svc.add_resource(vm1)
svc1.add_resource(vm2)
end
it 'cannot remove vms from services without an appropriate role' do
api_basic_authorize
run_post(services_url, 'action' => 'remove_resource')
expect(response).to have_http_status(:forbidden)
end
it 'can remove vms from multiple services by href with an appropriate role' do
api_basic_authorize collection_action_identifier(:services, :remove_resource)
request = {
'action' => 'remove_resource',
'resources' => [
{ 'href' => services_url(svc.id), 'resource' => { 'href' => vms_url(vm1.id)} },
{ 'href' => services_url(svc1.id), 'resource' => { 'href' => vms_url(vm2.id)} }
]
}
run_post(services_url, request)
expected = {
'results' => [
{ 'success' => true, 'message' => "Unassigned resource vms id:#{vm1.id} from Service id:#{svc.id} name:'#{svc.name}'" },
{ 'success' => true, 'message' => "Unassigned resource vms id:#{vm2.id} from Service id:#{svc1.id} name:'#{svc1.name}'" }
]
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
expect(svc.reload.service_resources).to eq([])
expect(svc1.reload.service_resources).to eq([])
end
it 'requires a service id to be specified' do
api_basic_authorize collection_action_identifier(:services, :remove_resource)
request = {
'action' => 'remove_resource',
'resources' => [
{ 'href' => services_url, 'resource' => { 'href' => vms_url(vm1.id)} }
]
}
run_post(services_url, request)
expected = {
'results' => [
{ 'success' => false, 'message' => 'Must specify a resource to remove_resource from' }
]
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
end
it 'requires that a resource be specified' do
api_basic_authorize collection_action_identifier(:services, :remove_resource)
request = {
'action' => 'remove_resource',
'resources' => [
{ 'href' => services_url(svc.id), 'resource' => {} }
]
}
run_post(services_url, request)
expected = {
'results' => [
{ 'success' => false, 'message' => 'Must specify a resource reference' }
]
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
end
it 'cannot remove a vm from a service without an appropriate role' do
api_basic_authorize
run_post(services_url(svc.id), 'action' => 'remove_resource')
expect(response).to have_http_status(:forbidden)
end
it 'can remove a vm from a service by href with an appropriate role' do
api_basic_authorize collection_action_identifier(:services, :remove_resource)
request = {
'action' => 'remove_resource',
'resource' => { 'resource' => {'href' => vms_url(vm1.id)} }
}
run_post(services_url(svc.id), request)
expected = {
'success' => true,
'message' => "Unassigned resource vms id:#{vm1.id} from Service id:#{svc.id} name:'#{svc.name}'"
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
expect(svc.reload.service_resources).to eq([])
end
end
describe 'remove_all_resources' do
let(:vm1) { FactoryGirl.create(:vm_vmware) }
let(:vm2) { FactoryGirl.create(:vm_vmware) }
let(:vm3) { FactoryGirl.create(:vm_vmware) }
before do
svc.add_resource(vm1)
svc.add_resource(vm2)
svc1.add_resource(vm3)
end
it 'cannot remove all resources without an appropriate role' do
api_basic_authorize
run_post(services_url, 'action' => 'remove_all_resources')
expect(response).to have_http_status(:forbidden)
end
it 'can remove all resources from multiple services' do
api_basic_authorize collection_action_identifier(:services, :remove_all_resources)
request = {
'action' => 'remove_all_resources',
'resources' => [
{ 'href' => services_url(svc.id) },
{ 'href' => services_url(svc1.id) }
]
}
run_post(services_url, request)
expected = {
'results' => [
{ 'success' => true, 'message' => "Removed all resources from Service id:#{svc.id} name:'#{svc.name}'"},
{ 'success' => true, 'message' => "Removed all resources from Service id:#{svc1.id} name:'#{svc1.name}'"}
]
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
expect(svc.reload.service_resources).to eq([])
expect(svc1.reload.service_resources).to eq([])
end
it 'cannot remove all resources without an appropriate role' do
api_basic_authorize
run_post(services_url(svc.id), :action => 'remove_all_resources')
expect(response).to have_http_status(:forbidden)
end
it 'can remove all resources from a service' do
api_basic_authorize collection_action_identifier(:services, :remove_all_resources)
run_post(services_url(svc.id), :action => 'remove_all_resources')
expected = {
'success' => true, 'message' => "Removed all resources from Service id:#{svc.id} name:'#{svc.name}'"
}
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(expected)
expect(svc.reload.service_resources).to eq([])
end
end
end
| 37.790675 | 132 | 0.621532 |
084dcb6895222ed7bb71a97e5d1d520bb0ec52f7 | 1,128 | cask "netnewswire-beta" do
version "6.1b3"
sha256 "dfd6bcad17e7f379b8efc1a73de5c3b3890d6f52784cf95f2f0d0b8411fe26cd"
url "https://github.com/brentsimmons/NetNewsWire/releases/download/mac-#{version}/NetNewsWire#{version}.zip",
verified: "github.com/brentsimmons/NetNewsWire/"
name "NetNewsWire"
desc "Free and open-source RSS reader"
homepage "https://ranchero.com/netnewswire/"
livecheck do
url :url
strategy :git
regex(/^mac-(\d+(?:\.\d+)*b\d+)$/i)
end
auto_updates true
conflicts_with cask: "netnewswire"
depends_on macos: ">= :catalina"
app "NetNewsWire.app"
zap trash: [
"~/Library/Application Scripts/com.ranchero.NetNewsWire-Evergreen.Subscribe-to-Feed",
"~/Library/Application Support/NetNewsWire",
"~/Library/Caches/com.ranchero.NetNewsWire-Evergreen",
"~/Library/Containers/com.ranchero.NetNewsWire-Evergreen.Subscribe-to-Feed",
"~/Library/Preferences/com.ranchero.NetNewsWire-Evergreen.plist",
"~/Library/Saved Application State/com.ranchero.NetNewsWire-Evergreen.savedState",
"~/Library/WebKit/com.ranchero.NetNewsWire-Evergreen",
]
end
| 34.181818 | 111 | 0.735816 |
03a5d50befdac1cea51ef4eb0c555aa485d3880a | 2,149 | module Recurly
class BillingInfo < Resource
BANK_ACCOUNT_ATTRIBUTES = %w(name_on_account account_type last_four routing_number).freeze
CREDIT_CARD_ATTRIBUTES = %w(number verification_value card_type year month first_six last_four).freeze
AMAZON_ATTRIBUTES = %w(amazon_billing_agreement_id).freeze
PAYPAL_ATTRIBUTES = %w(paypal_billing_agreement_id).freeze
# @return [Account]
belongs_to :account
define_attribute_methods %w(
first_name
last_name
company
address1
address2
city
state
zip
country
phone
vat_number
ip_address
ip_address_country
token_id
currency
) | CREDIT_CARD_ATTRIBUTES | BANK_ACCOUNT_ATTRIBUTES | AMAZON_ATTRIBUTES | PAYPAL_ATTRIBUTES
# @return ["credit_card", "paypal", "amazon", "bank_account", nil] The type of billing info.
attr_reader :type
# @return [String]
def inspect
attributes = self.class.attribute_names
case type
when 'credit_card'
attributes -= (AMAZON_ATTRIBUTES + PAYPAL_ATTRIBUTES + BANK_ACCOUNT_ATTRIBUTES)
attributes |= CREDIT_CARD_ATTRIBUTES
when 'paypal'
attributes -= (CREDIT_CARD_ATTRIBUTES | BANK_ACCOUNT_ATTRIBUTES + AMAZON_ATTRIBUTES)
when 'amazon'
attributes -= (CREDIT_CARD_ATTRIBUTES | BANK_ACCOUNT_ATTRIBUTES + PAYPAL_ATTRIBUTES)
when 'bank_account'
attributes -= (CREDIT_CARD_ATTRIBUTES + PAYPAL_ATTRIBUTES + AMAZON_ATTRIBUTES)
attributes |= BANK_ACCOUNT_ATTRIBUTES
end
super attributes
end
class << self
# Overrides the inherited member_path method to allow for billing info's
# irregular URL structure.
#
# @return [String] The relative path to an account's billing info from the
# API's base URI.
# @param uuid [String]
# @example
# Recurly::BillingInfo.member_path "code"
# # => "accounts/code/billing_info"
def member_path uuid
"accounts/#{uuid}/billing_info"
end
end
# Billing info is only writeable through an {Account} instance.
embedded!
end
end
| 31.144928 | 106 | 0.683108 |
bf9bd862e2f5c2645b0947aa0cf5b884b9e2e75c | 2,246 | # 28a8cfadda13f496447dae5b5a346be1
# Generated: 2008-09-22 16:25:10
################################################################################
# require File.dirname(__FILE__) + '/../../spec_helper'
# require File.dirname(__FILE__) + '/fixtures/classes'
#
# describe "Array#shift" do
# it "removes and returns the first element" do
# a = [5, 1, 1, 5, 4]
# a.shift.should == 5
# a.should == [1, 1, 5, 4]
# a.shift.should == 1
# a.should == [1, 5, 4]
# a.shift.should == 1
# a.should == [5, 4]
# a.shift.should == 5
# a.should == [4]
# a.shift.should == 4
# a.should == []
# end
#
# it "returns nil when the array is empty" do
# [].shift.should == nil
# end
#
# it "properly handles recursive arrays" do
# empty = ArraySpecs.empty_recursive_array
# empty.shift.should == []
# empty.should == []
#
# array = ArraySpecs.recursive_array
# array.shift.should == 1
# array[0..2].should == ['two', 3.0, array]
# end
#
# compliant_on :ruby, :jruby do
# it "raises a TypeError on a frozen array" do
# lambda { ArraySpecs.frozen_array.shift }.should raise_error(TypeError)
# end
# end
# end
puts 'not implemented: shift_spec.rb'
unless true
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'
describe "Array#shift" do
it "removes and returns the first element" do
a = [5, 1, 1, 5, 4]
a.shift.should == 5
a.should == [1, 1, 5, 4]
a.shift.should == 1
a.should == [1, 5, 4]
a.shift.should == 1
a.should == [5, 4]
a.shift.should == 5
a.should == [4]
a.shift.should == 4
a.should == []
end
it "returns nil when the array is empty" do
[].shift.should == nil
end
it "properly handles recursive arrays" do
empty = ArraySpecs.empty_recursive_array
empty.shift.should == []
empty.should == []
array = ArraySpecs.recursive_array
array.shift.should == 1
array[0..2].should == ['two', 3.0, array]
end
compliant_on :ruby, :jruby do
it "raises a TypeError on a frozen array" do
lambda { ArraySpecs.frozen_array.shift }.should raise_error(TypeError)
end
end
end
end # remove with unless true
| 26.738095 | 80 | 0.58504 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.