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
|
---|---|---|---|---|---|
38f33169b0fc597d6ff0752722b05fe2b2dffea0 | 595 | require 'logger'
require 'active_record/base'
module TestHelper
module ActiveRecord
private
def setup_schema
::ActiveRecord::Base.class_eval do
connection.instance_eval do
create_table :users, :force => true do |t|
t.string :name
t.string :email
t.timestamps null: false
end
end
end
end
class User < ::ActiveRecord::Base ; end
end
end
ActiveRecord::Base.logger = Logger.new(TestHelper::LogHelpers::LOG)
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
| 20.517241 | 80 | 0.642017 |
61a2be692d7e32091d679a53f0ffa4f38120275f | 558 | # WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
$:.unshift(File.expand_path('../../lib', __FILE__))
$:.unshift(File.expand_path('../../../aws-sdk-core/features', __FILE__))
$:.unshift(File.expand_path('../../../aws-sdk-core/lib', __FILE__))
$:.unshift(File.expand_path('../../../aws-sigv4/lib', __FILE__))
require 'features_helper'
require 'aws-sdk-mq'
Aws::MQ::Client.add_plugin(ApiCallTracker)
| 32.823529 | 74 | 0.713262 |
0329717448016423a657b296c209c9db9966fee9 | 965 | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "httparty/version"
Gem::Specification.new do |s|
s.name = "httparty"
s.version = HTTParty::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["John Nunemaker", "Sandro Turriate"]
s.email = ["[email protected]"]
s.homepage = "http://jnunemaker.github.com/httparty"
s.summary = %q{Makes http fun! Also, makes consuming restful web services dead easy.}
s.description = %q{Makes http fun! Also, makes consuming restful web services dead easy.}
s.add_dependency 'multi_json', "~> 1.0"
s.add_dependency 'multi_xml', ">= 0.5.2"
s.post_install_message = "When you HTTParty, you must party hard!"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
| 38.6 | 91 | 0.639378 |
1a895fc0989504e6e6f862e52b843296e55333e5 | 1,131 | # encoding: utf-8
require 'spec_helper'
describe Github::Activity::Starring, '#list' do
let(:user) { 'peter-murach' }
let(:repo) { 'github' }
let(:request_path) { "/user/starred/#{user}/#{repo}" }
after { reset_authentication_for subject }
context "with username ane reponame passed" do
context "this repo is being watched by the user"
before do
stub_get(request_path).
to_return(:body => "[]", :status => 404,
:headers => {:user_agent => subject.user_agent})
end
it "should return false if resource not found" do
starring = subject.starring? user, repo
starring.should be_false
end
it "should return true if resoure found" do
stub_get(request_path).to_return(:body => "[]", :status => 200,
:headers => {:user_agent => subject.user_agent})
starring = subject.starring? user, repo
starring.should be_true
end
end
context "without username and reponame passed" do
it "should fail validation " do
expect { subject.starring? user }.to raise_error(ArgumentError)
end
end
end # starring?
| 29 | 71 | 0.64191 |
1cfcb18a2714d8118150d71286103a219b9a0531 | 579 | class AddTrophiesTable < ActiveRecord::Migration
def change
create_table :trophies do |t|
t.string :name
t.string :image_name
t.timestamps
end
create_table :user_trophies do |t|
t.references :user, null: false
t.references :trophy, null: false
t.references :concept, null: true
t.timestamps
end
add_index :trophies, :name, unique: true
add_index :user_trophies, [:user_id, :trophy_id, :concept_id], unique: true
Activity.connection.execute('alter table activities modify data varchar(8192)')
end
end
| 24.125 | 83 | 0.682211 |
26cab7b637c4c02b6c49a8d0ae4cf5b509e62999 | 691 | class Sec < Formula
desc "Event correlation tool for event processing of various kinds"
homepage "https://simple-evcorr.sourceforge.io/"
url "https://github.com/simple-evcorr/sec/releases/download/2.9.1/sec-2.9.1.tar.gz"
sha256 "63a4125930a7dc8d71ee67f2ebb42e607ac0c66216e1349f279ece8f28720a34"
license "GPL-2.0-or-later"
bottle do
root_url "https://github.com/gromgit/homebrew-core-mojave/releases/download/sec"
sha256 cellar: :any_skip_relocation, mojave: "30b242f22b62c67d6b5e862fd9884ec05b327e33ee6d146137b3566e0d2a178b"
end
def install
bin.install "sec"
man1.install "sec.man" => "sec.1"
end
test do
system "#{bin}/sec", "--version"
end
end
| 31.409091 | 115 | 0.746744 |
bfd7499893f3b751ca18027ce477d30b65a017c9 | 659 | # Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure your secret_key_base is kept private
# if you're sharing your code publicly.
Dummy::Application.config.secret_key_base = '2ff282a81eb56f2739643daef0aec3534156a15cd4f9b996ad39598a37e12a42ef2b2467f2c448a0b245762e654ce0496752fd6d75ea5e62891410f0cd98b237'
| 50.692308 | 174 | 0.814871 |
1d4b0430931de760d8cfe5329c87affb006fdf54 | 1,683 | shared_examples_for "a baza indexes driver" do
let(:driver) { constant.new }
let(:db) { driver.db }
let(:test_table) do
db.tables.create(
"test",
columns: [
{name: "id", type: :int, autoincr: true, primarykey: true},
{name: "text", type: :varchar},
{name: "email", type: :varchar}
],
indexes: [
:text,
{name: :email, unique: true, columns: [:email]},
{name: :two_columns, columns: [:text, :email]}
]
)
db.tables[:test]
end
before do
driver.before
end
after do
driver.after
end
it "renames indexes for renamed tables" do
# Load up columns to make them set table-name.
test_table.indexes.each do |name, index|
end
test_table.create_indexes([{name: "index_on_text", columns: [:text]}])
test_table.rename("test2")
test_table.index("index_on_text").rename("index_on_text2")
table = db.tables[:test2]
index = table.index(:index_on_text2)
expect(index.table.name).to eq "test2"
end
it "raises an error when an index isn't found" do
expect do
test_table.index("index_that_doesnt_exist")
end.to raise_error(Baza::Errors::IndexNotFound)
end
describe Baza::Index do
describe "#unique?" do
it "returns true when it is unique" do
expect(test_table.index("email").unique?).to eq true
end
it "returns false when it isn't unique" do
expect(test_table.index("text").unique?).to eq false
end
end
describe "#columns" do
it "returns the correct columns" do
expect(test_table.index("two_columns").columns).to eq %w(text email)
end
end
end
end
| 25.119403 | 76 | 0.621509 |
f836d45d0e88285d6968321c42cd70847e6f555c | 34,377 | module ActiveRecord
module Associations
# Association proxies in Active Record are middlemen between the object that
# holds the association, known as the <tt>@owner</tt>, and the actual associated
# object, known as the <tt>@target</tt>. The kind of association any proxy is
# about is available in <tt>@reflection</tt>. That's an instance of the class
# ActiveRecord::Reflection::AssociationReflection.
#
# For example, given
#
# class Blog < ActiveRecord::Base
# has_many :posts
# end
#
# blog = Blog.first
#
# the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
# <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
# the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
#
# This class delegates unknown methods to <tt>@target</tt> via
# <tt>method_missing</tt>.
#
# The <tt>@target</tt> object is not \loaded until needed. For example,
#
# blog.posts.count
#
# is computed directly through SQL and does not trigger by itself the
# instantiation of the actual post records.
class CollectionProxy < Relation
delegate(*(ActiveRecord::Calculations.public_instance_methods - [:count]), to: :scope)
def initialize(klass, association) #:nodoc:
@association = association
super klass, klass.arel_table
merge! association.scope(nullify: false)
end
def target
@association.target
end
def load_target
@association.load_target
end
# Returns +true+ if the association has been loaded, otherwise +false+.
#
# person.pets.loaded? # => false
# person.pets
# person.pets.loaded? # => true
def loaded?
@association.loaded?
end
# Works in two ways.
#
# *First:* Specify a subset of fields to be selected from the result set.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.select(:name)
# # => [
# # #<Pet id: nil, name: "Fancy-Fancy">,
# # #<Pet id: nil, name: "Spook">,
# # #<Pet id: nil, name: "Choo-Choo">
# # ]
#
# person.pets.select([:id, :name])
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy">,
# # #<Pet id: 2, name: "Spook">,
# # #<Pet id: 3, name: "Choo-Choo">
# # ]
#
# Be careful because this also means you're initializing a model
# object with only the fields that you've selected. If you attempt
# to access a field that is not in the initialized record you'll
# receive:
#
# person.pets.select(:name).first.person_id
# # => ActiveModel::MissingAttributeError: missing attribute: person_id
#
# *Second:* You can pass a block so it can be used just like Array#select.
# This builds an array of objects from the database for the scope,
# converting them into an array and iterating through them using
# Array#select.
#
# person.pets.select { |pet| pet.name =~ /oo/ }
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.select(:name) { |pet| pet.name =~ /oo/ }
# # => [
# # #<Pet id: 2, name: "Spook">,
# # #<Pet id: 3, name: "Choo-Choo">
# # ]
def select(select = nil, &block)
@association.select(select, &block)
end
# Finds an object in the collection responding to the +id+. Uses the same
# rules as <tt>ActiveRecord::Base.find</tt>. Returns <tt>ActiveRecord::RecordNotFound</tt>
# error if the object can not be found.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.find(1) # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
# person.pets.find(4) # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=4
#
# person.pets.find(2) { |pet| pet.name.downcase! }
# # => #<Pet id: 2, name: "fancy-fancy", person_id: 1>
#
# person.pets.find(2, 3)
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
def find(*args, &block)
@association.find(*args, &block)
end
# Returns the first record, or the first +n+ records, from the collection.
# If the collection is empty, the first form returns +nil+, and the second
# form returns an empty array.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.first # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
#
# person.pets.first(2)
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>
# # ]
#
# another_person_without.pets # => []
# another_person_without.pets.first # => nil
# another_person_without.pets.first(3) # => []
def first(*args)
@association.first(*args)
end
# Returns the last record, or the last +n+ records, from the collection.
# If the collection is empty, the first form returns +nil+, and the second
# form returns an empty array.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.last # => #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#
# person.pets.last(2)
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# another_person_without.pets # => []
# another_person_without.pets.last # => nil
# another_person_without.pets.last(3) # => []
def last(*args)
@association.last(*args)
end
# Returns a new object of the collection type that has been instantiated
# with +attributes+ and linked to this object, but have not yet been saved.
# You can pass an array of attributes hashes, this will return an array
# with the new objects.
#
# class Person
# has_many :pets
# end
#
# person.pets.build
# # => #<Pet id: nil, name: nil, person_id: 1>
#
# person.pets.build(name: 'Fancy-Fancy')
# # => #<Pet id: nil, name: "Fancy-Fancy", person_id: 1>
#
# person.pets.build([{name: 'Spook'}, {name: 'Choo-Choo'}, {name: 'Brain'}])
# # => [
# # #<Pet id: nil, name: "Spook", person_id: 1>,
# # #<Pet id: nil, name: "Choo-Choo", person_id: 1>,
# # #<Pet id: nil, name: "Brain", person_id: 1>
# # ]
#
# person.pets.size # => 5 # size of the collection
# person.pets.count # => 0 # count from database
def build(attributes = {}, &block)
@association.build(attributes, &block)
end
alias_method :new, :build
# Returns a new object of the collection type that has been instantiated with
# attributes, linked to this object and that has already been saved (if it
# passes the validations).
#
# class Person
# has_many :pets
# end
#
# person.pets.create(name: 'Fancy-Fancy')
# # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
#
# person.pets.create([{name: 'Spook'}, {name: 'Choo-Choo'}])
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.size # => 3
# person.pets.count # => 3
#
# person.pets.find(1, 2, 3)
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
def create(attributes = {}, &block)
@association.create(attributes, &block)
end
# Like +create+, except that if the record is invalid, raises an exception.
#
# class Person
# has_many :pets
# end
#
# class Pet
# validates :name, presence: true
# end
#
# person.pets.create!(name: nil)
# # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
def create!(attributes = {}, &block)
@association.create!(attributes, &block)
end
# Add one or more records to the collection by setting their foreign keys
# to the association's primary key. Since << flattens its argument list and
# inserts each record, +push+ and +concat+ behave identically. Returns +self+
# so method calls may be chained.
#
# class Person < ActiveRecord::Base
# pets :has_many
# end
#
# person.pets.size # => 0
# person.pets.concat(Pet.new(name: 'Fancy-Fancy'))
# person.pets.concat(Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo'))
# person.pets.size # => 3
#
# person.id # => 1
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.concat([Pet.new(name: 'Brain'), Pet.new(name: 'Benny')])
# person.pets.size # => 5
def concat(*records)
@association.concat(*records)
end
# Replaces this collection with +other_array+. This will perform a diff
# and delete/add only records that have changed.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets
# # => [#<Pet id: 1, name: "Gorby", group: "cats", person_id: 1>]
#
# other_pets = [Pet.new(name: 'Puff', group: 'celebrities']
#
# person.pets.replace(other_pets)
#
# person.pets
# # => [#<Pet id: 2, name: "Puff", group: "celebrities", person_id: 1>]
#
# If the supplied array has an incorrect association type, it raises
# an <tt>ActiveRecord::AssociationTypeMismatch</tt> error:
#
# person.pets.replace(["doo", "ggie", "gaga"])
# # => ActiveRecord::AssociationTypeMismatch: Pet expected, got String
def replace(other_array)
@association.replace(other_array)
end
# Deletes all the records from the collection. For +has_many+ associations,
# the deletion is done according to the strategy specified by the <tt>:dependent</tt>
# option. Returns an array with the deleted records.
#
# If no <tt>:dependent</tt> option is given, then it will follow the
# default strategy. The default strategy is <tt>:nullify</tt>. This
# sets the foreign keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>,
# the default strategy is +delete_all+.
#
# class Person < ActiveRecord::Base
# has_many :pets # dependent: :nullify option by default
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete_all
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.size # => 0
# person.pets # => []
#
# Pet.find(1, 2, 3)
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>,
# # #<Pet id: 2, name: "Spook", person_id: nil>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: nil>
# # ]
#
# If it is set to <tt>:destroy</tt> all the objects from the collection
# are removed by calling their +destroy+ method. See +destroy+ for more
# information.
#
# class Person < ActiveRecord::Base
# has_many :pets, dependent: :destroy
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete_all
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# Pet.find(1, 2, 3)
# # => ActiveRecord::RecordNotFound
#
# If it is set to <tt>:delete_all</tt>, all the objects are deleted
# *without* calling their +destroy+ method.
#
# class Person < ActiveRecord::Base
# has_many :pets, dependent: :delete_all
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete_all
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# Pet.find(1, 2, 3)
# # => ActiveRecord::RecordNotFound
def delete_all
@association.delete_all
end
# Deletes the records of the collection directly from the database
# ignoring the +:dependent+ option. It invokes +before_remove+,
# +after_remove+ , +before_destroy+ and +after_destroy+ callbacks.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.destroy_all
#
# person.pets.size # => 0
# person.pets # => []
#
# Pet.find(1) # => Couldn't find Pet with id=1
def destroy_all
@association.destroy_all
end
# Deletes the +records+ supplied and removes them from the collection. For
# +has_many+ associations, the deletion is done according to the strategy
# specified by the <tt>:dependent</tt> option. Returns an array with the
# deleted records.
#
# If no <tt>:dependent</tt> option is given, then it will follow the default
# strategy. The default strategy is <tt>:nullify</tt>. This sets the foreign
# keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>, the default
# strategy is +delete_all+.
#
# class Person < ActiveRecord::Base
# has_many :pets # dependent: :nullify option by default
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete(Pet.find(1))
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
#
# person.pets.size # => 2
# person.pets
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# Pet.find(1)
# # => #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>
#
# If it is set to <tt>:destroy</tt> all the +records+ are removed by calling
# their +destroy+ method. See +destroy+ for more information.
#
# class Person < ActiveRecord::Base
# has_many :pets, dependent: :destroy
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete(Pet.find(1), Pet.find(3))
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.size # => 1
# person.pets
# # => [#<Pet id: 2, name: "Spook", person_id: 1>]
#
# Pet.find(1, 3)
# # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 3)
#
# If it is set to <tt>:delete_all</tt>, all the +records+ are deleted
# *without* calling their +destroy+ method.
#
# class Person < ActiveRecord::Base
# has_many :pets, dependent: :delete_all
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete(Pet.find(1))
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
#
# person.pets.size # => 2
# person.pets
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# Pet.find(1)
# # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=1
#
# You can pass +Fixnum+ or +String+ values, it finds the records
# responding to the +id+ and executes delete on them.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete("1")
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
#
# person.pets.delete(2, 3)
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
def delete(*records)
@association.delete(*records)
end
# Destroys the +records+ supplied and removes them from the collection.
# This method will _always_ remove record from the database ignoring
# the +:dependent+ option. Returns an array with the removed records.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.destroy(Pet.find(1))
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
#
# person.pets.size # => 2
# person.pets
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.destroy(Pet.find(2), Pet.find(3))
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.size # => 0
# person.pets # => []
#
# Pet.find(1, 2, 3) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 2, 3)
#
# You can pass +Fixnum+ or +String+ values, it finds the records
# responding to the +id+ and then deletes them from the database.
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 4, name: "Benny", person_id: 1>,
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
#
# person.pets.destroy("4")
# # => #<Pet id: 4, name: "Benny", person_id: 1>
#
# person.pets.size # => 2
# person.pets
# # => [
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
#
# person.pets.destroy(5, 6)
# # => [
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
#
# person.pets.size # => 0
# person.pets # => []
#
# Pet.find(4, 5, 6) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (4, 5, 6)
def destroy(*records)
@association.destroy(*records)
end
# Specifies whether the records should be unique or not.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.select(:name)
# # => [
# # #<Pet name: "Fancy-Fancy">,
# # #<Pet name: "Fancy-Fancy">
# # ]
#
# person.pets.select(:name).distinct
# # => [#<Pet name: "Fancy-Fancy">]
def distinct
@association.distinct
end
alias uniq distinct
# Count all records using SQL.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.count # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
def count(column_name = nil, options = {})
@association.count(column_name, options)
end
# Returns the size of the collection. If the collection hasn't been loaded,
# it executes a <tt>SELECT COUNT(*)</tt> query. Else it calls <tt>collection.size</tt>.
#
# If the collection has been already loaded +size+ and +length+ are
# equivalent. If not and you are going to need the records anyway
# +length+ will take one less query. Otherwise +size+ is more efficient.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.size # => 3
# # executes something like SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" = 1
#
# person.pets # This will execute a SELECT * FROM query
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.size # => 3
# # Because the collection is already loaded, this will behave like
# # collection.size and no SQL count query is executed.
def size
@association.size
end
# Returns the size of the collection calling +size+ on the target.
# If the collection has been already loaded, +length+ and +size+ are
# equivalent. If not and you are going to need the records anyway this
# method will take one less query. Otherwise +size+ is more efficient.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.length # => 3
# # executes something like SELECT "pets".* FROM "pets" WHERE "pets"."person_id" = 1
#
# # Because the collection is loaded, you can
# # call the collection with no additional queries:
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
def length
@association.length
end
# Returns +true+ if the collection is empty. If the collection has been
# loaded or the <tt>:counter_sql</tt> option is provided, it is equivalent
# to <tt>collection.size.zero?</tt>. If the collection has not been loaded,
# it is equivalent to <tt>collection.exists?</tt>. If the collection has
# not already been loaded and you are going to fetch the records anyway it
# is better to check <tt>collection.length.zero?</tt>.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.count # => 1
# person.pets.empty? # => false
#
# person.pets.delete_all
#
# person.pets.count # => 0
# person.pets.empty? # => true
def empty?
@association.empty?
end
# Returns +true+ if the collection is not empty.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.count # => 0
# person.pets.any? # => false
#
# person.pets << Pet.new(name: 'Snoop')
# person.pets.count # => 0
# person.pets.any? # => true
#
# You can also pass a block to define criteria. The behavior
# is the same, it returns true if the collection based on the
# criteria is not empty.
#
# person.pets
# # => [#<Pet name: "Snoop", group: "dogs">]
#
# person.pets.any? do |pet|
# pet.group == 'cats'
# end
# # => false
#
# person.pets.any? do |pet|
# pet.group == 'dogs'
# end
# # => true
def any?(&block)
@association.any?(&block)
end
# Returns true if the collection has more than one record.
# Equivalent to <tt>collection.size > 1</tt>.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.count #=> 1
# person.pets.many? #=> false
#
# person.pets << Pet.new(name: 'Snoopy')
# person.pets.count #=> 2
# person.pets.many? #=> true
#
# You can also pass a block to define criteria. The
# behavior is the same, it returns true if the collection
# based on the criteria has more than one record.
#
# person.pets
# # => [
# # #<Pet name: "Gorby", group: "cats">,
# # #<Pet name: "Puff", group: "cats">,
# # #<Pet name: "Snoop", group: "dogs">
# # ]
#
# person.pets.many? do |pet|
# pet.group == 'dogs'
# end
# # => false
#
# person.pets.many? do |pet|
# pet.group == 'cats'
# end
# # => true
def many?(&block)
@association.many?(&block)
end
# Returns +true+ if the given object is present in the collection.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets # => [#<Pet id: 20, name: "Snoop">]
#
# person.pets.include?(Pet.find(20)) # => true
# person.pets.include?(Pet.find(21)) # => false
def include?(record)
[email protected]?(record)
end
def proxy_association
@association
end
# We don't want this object to be put on the scoping stack, because
# that could create an infinite loop where we call an @association
# method, which gets the current scope, which is this object, which
# delegates to @association, and so on.
def scoping
@association.scope.scoping { yield }
end
# Returns a <tt>Relation</tt> object for the records in this association
def scope
@association.scope
end
# :nodoc:
alias spawn scope
# Equivalent to <tt>Array#==</tt>. Returns +true+ if the two arrays
# contain the same number of elements and if each element is equal
# to the corresponding element in the other array, otherwise returns
# +false+.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>
# # ]
#
# other = person.pets.to_ary
#
# person.pets == other
# # => true
#
# other = [Pet.new(id: 1), Pet.new(id: 2)]
#
# person.pets == other
# # => false
def ==(other)
load_target == other
end
# Returns a new array of objects from the collection. If the collection
# hasn't been loaded, it fetches the records from the database.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets
# # => [
# # #<Pet id: 4, name: "Benny", person_id: 1>,
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
#
# other_pets = person.pets.to_ary
# # => [
# # #<Pet id: 4, name: "Benny", person_id: 1>,
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
#
# other_pets.replace([Pet.new(name: 'BooGoo')])
#
# other_pets
# # => [#<Pet id: nil, name: "BooGoo", person_id: 1>]
#
# person.pets
# # This is not affected by replace
# # => [
# # #<Pet id: 4, name: "Benny", person_id: 1>,
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
def to_ary
load_target.dup
end
alias_method :to_a, :to_ary
# Adds one or more +records+ to the collection by setting their foreign keys
# to the association's primary key. Returns +self+, so several appends may be
# chained together.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.size # => 0
# person.pets << Pet.new(name: 'Fancy-Fancy')
# person.pets << [Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo')]
# person.pets.size # => 3
#
# person.id # => 1
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
def <<(*records)
proxy_association.concat(records) && self
end
alias_method :push, :<<
alias_method :append, :<<
def prepend(*args)
raise NoMethodError, "prepend on association is not defined. Please use << or append"
end
# Equivalent to +delete_all+. The difference is that returns +self+, instead
# of an array with the deleted objects, so methods can be chained. See
# +delete_all+ for more information.
def clear
delete_all
self
end
# Reloads the collection from the database. Returns +self+.
# Equivalent to <tt>collection(true)</tt>.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets # fetches pets from the database
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
#
# person.pets # uses the pets cache
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
#
# person.pets.reload # fetches pets from the database
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
#
# person.pets(true) # fetches pets from the database
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
def reload
proxy_association.reload
self
end
end
end
end
| 34.935976 | 104 | 0.49792 |
ed23c8a4a2c2f9be31e6d5d6e511898cb07a69c3 | 305 | module Ecommerce
class Wishlist < ApplicationRecord
belongs_to :user, optional: true
has_many :wishlist_items
enum status: {active: 1, closed: 2}
def add_wishlist_items(item_params)
WishlistItem.create(user_id: current_user, product: item_params[:product_id])
end
end
end
| 21.785714 | 83 | 0.731148 |
bfde964b1a8c73af3de5b218cfb3be5d86ac8093 | 348 | cask 'font-noto-sans-devanagari' do
version :latest
sha256 :no_check
url 'https://noto-website-2.storage.googleapis.com/pkgs/NotoSansDevanagari-unhinted.zip'
name 'Noto Sans Devanagari'
homepage 'https://www.google.com/get/noto/#sans-deva'
license :ofl
font 'NotoSansDevanagari-Bold.ttf'
font 'NotoSansDevanagari-Regular.ttf'
end
| 26.769231 | 90 | 0.758621 |
6abd2ab80fb3090e2aebb9981e6e3e0b2b534dfa | 278 | module PeopleApiStub
module_function
def setup(attributes = {})
attributes.reverse_merge! FactoryBot.attributes_for(:ldap_entry)
WebMock.
stub_request(:get, Regexp.new(PeopleApi::URI.host)).
to_return(status: 200, body: [attributes].to_json)
end
end
| 23.166667 | 68 | 0.723022 |
ed7523d963c4d5dbf2c9e6d624a4d3c344fcc304 | 590 | # frozen_string_literal: true
describe 'Sles MemorySwapAvailableBytes' do
context '#call_the_resolver' do
it 'returns a fact' do
expected_fact = double(Facter::ResolvedFact, name: 'memory.swap.available_bytes', value: 1024)
allow(Facter::Resolvers::Linux::Memory).to receive(:resolve).with(:swap_free).and_return(1024)
allow(Facter::ResolvedFact).to receive(:new).with('memory.swap.available_bytes', 1024).and_return(expected_fact)
fact = Facter::Sles::MemorySwapAvailableBytes.new
expect(fact.call_the_resolver).to eq(expected_fact)
end
end
end
| 39.333333 | 118 | 0.744068 |
616358a589753b4ccc54ee6ef751063fb3ee5f13 | 203 | class AddMeetingsTextToCommittees < ActiveRecord::Migration
def self.up
add_column :committees, :meetings_text, :text
end
def self.down
remove_column :committees, :meetings_text
end
end
| 20.3 | 59 | 0.763547 |
2676bf19bc9fa91104cf0def9db85cc83ecede56 | 1,714 | module Appsignal
class Hooks
# @api private
class DelayedJobPlugin < ::Delayed::Plugin
extend Appsignal::Hooks::Helpers
callbacks do |lifecycle|
lifecycle.around(:invoke_job) do |job, &block|
invoke_with_instrumentation(job, block)
end
lifecycle.after(:execute) do |_execute|
Appsignal.stop("delayed job")
end
end
def self.invoke_with_instrumentation(job, block)
payload = job.payload_object
if payload.respond_to? :job_data
# ActiveJob
job_data = payload.job_data
args = job_data.fetch("arguments", {})
class_name = job_data["job_class"]
method_name = "perform"
else
# Delayed Job
args = extract_value(job.payload_object, :args, {})
class_and_method_name = extract_value(job.payload_object, :appsignal_name, job.name)
class_name, method_name = class_and_method_name.split("#")
end
params = Appsignal::Utils::ParamsSanitizer.sanitize args,
:filter_parameters => Appsignal.config[:filter_parameters]
Appsignal.monitor_transaction(
"perform_job.delayed_job",
:class => class_name,
:method => method_name,
:metadata => {
:id => extract_value(job, :id, nil, true),
:queue => extract_value(job, :queue),
:priority => extract_value(job, :priority, 0),
:attempts => extract_value(job, :attempts, 0)
},
:params => params,
:queue_start => extract_value(job, :run_at)
) do
block.call(job)
end
end
end
end
end
| 31.163636 | 94 | 0.582264 |
0867cdd422a5a1565aa1fa842b0ebd071b114826 | 661 | require 'spec_helper'
describe RailsBestPractices::Core::Nil do
let(:core_nil) { RailsBestPractices::Core::Nil.new }
context "to_s" do
it "should return self" do
core_nil.to_s.should == core_nil
end
end
context "hash_size" do
it "should return 0" do
core_nil.hash_size.should == 0
end
end
context "method_missing" do
it "should return self" do
core_nil.undefined.should == core_nil
end
end
context "present?" do
it "should return false" do
core_nil.should_not be_present
end
end
context "blank?" do
it "should return true" do
core_nil.should be_blank
end
end
end
| 18.361111 | 54 | 0.662632 |
1c1b775632078b918d9c6545ff50bb6148c5b257 | 260 | require 'test_helper'
describe Merit::Score do
it 'Point#sash_id delegates to Score' do
score = Merit::Score.new
score.sash_id = 33
point = Merit::Score::Point.new
point.score = score
point.sash_id.must_be :==, score.sash_id
end
end
| 18.571429 | 44 | 0.680769 |
918a1fb3ad276d06de5b6ef825aa1d3bc3c6d7ec | 95 | # frozen_string_literal: true
class HelloWorld
def self.hello
'Hello, World!'
end
end
| 11.875 | 29 | 0.715789 |
62a4e9bd8a64f334e26d4f05145582ba65453bcd | 940 | Pod::Spec.new do |s|
s.name = "GzipSwift"
s.version = "4.0.4"
s.summary = "Swift framework that enables gzip/gunzip Data using zlib."
s.homepage = "https://github.com/1024jp/GzipSwift"
s.license = { :type => "MIT",
:file => "LICENSE" }
s.author = { "1024jp" => "[email protected]" }
s.social_media_url = "https://twitter.com/1024jp"
s.source = { :git => "https://github.com/1024jp/GzipSwift.git",
:tag => s.version }
s.source_files = 'Sources/Gzip/*.swift'
s.module_name = 'Gzip'
s.osx.deployment_target = '10.9'
s.ios.deployment_target = '8.0'
s.watchos.deployment_target = '2.0'
s.tvos.deployment_target = '9.0'
s.requires_arc = true
s.library = 'z'
s.pod_target_xcconfig = { 'APPLICATION_EXTENSION_API_ONLY' => 'YES' }
# NOTE: Protection
s.dependency '//+WrongSourceRepository'
end
| 32.413793 | 79 | 0.58617 |
264ffe1f3255dc0c32bd57a06f5141d69e1da52c | 185 | require 'rubygems'
require 'sinatra'
get '*' do
ip = request.env['REMOTE_ADDR']
"<html><head><title>#{ip}</title></head><body><h1>Your IP Address is #{ip}</h1></body></html>"
end
| 23.125 | 96 | 0.632432 |
61f3e6601fb891af7a3e494855fca1b167cd8c43 | 223 | require 'socket'
s = TCPServer.new(3939)
while (conn = s.accept)
Thread.new(conn) do |c|
c.print "Hi. What's your name? "
name = c.gets.chomp
c.puts "Hi, #{name}. Here's the date."
c.puts `date`
c.close
end
end
| 18.583333 | 40 | 0.632287 |
03f7573d59bb8bbcbe1bfc6b9ae7ebb40fb0e341 | 20,008 | describe FastlaneCore do
describe FastlaneCore::Project do
describe 'project and workspace detection' do
def within_a_temp_dir
Dir.mktmpdir do |dir|
FileUtils.cd(dir) do
yield(dir) if block_given?
end
end
end
let(:options) do
[
FastlaneCore::ConfigItem.new(key: :project, description: "Project", optional: true),
FastlaneCore::ConfigItem.new(key: :workspace, description: "Workspace", optional: true)
]
end
it 'raises if both project and workspace are specified' do
expect do
config = FastlaneCore::Configuration.new(options, { project: 'yup', workspace: 'yeah' })
FastlaneCore::Project.detect_projects(config)
end.to raise_error(FastlaneCore::Interface::FastlaneError, "You can only pass either a workspace or a project path, not both")
end
it 'keeps the specified project' do
config = FastlaneCore::Configuration.new(options, { project: 'yup' })
FastlaneCore::Project.detect_projects(config)
expect(config[:project]).to eq('yup')
expect(config[:workspace]).to be_nil
end
it 'keeps the specified workspace' do
config = FastlaneCore::Configuration.new(options, { workspace: 'yeah' })
FastlaneCore::Project.detect_projects(config)
expect(config[:project]).to be_nil
expect(config[:workspace]).to eq('yeah')
end
it 'picks the only workspace file present' do
within_a_temp_dir do |dir|
workspace = './Something.xcworkspace'
FileUtils.mkdir_p(workspace)
config = FastlaneCore::Configuration.new(options, {})
FastlaneCore::Project.detect_projects(config)
expect(config[:workspace]).to eq(workspace)
end
end
it 'picks the only project file present' do
within_a_temp_dir do |dir|
project = './Something.xcodeproj'
FileUtils.mkdir_p(project)
config = FastlaneCore::Configuration.new(options, {})
FastlaneCore::Project.detect_projects(config)
expect(config[:project]).to eq(project)
end
end
it 'prompts to select among multiple workspace files' do
within_a_temp_dir do |dir|
workspaces = ['./Something.xcworkspace', './SomethingElse.xcworkspace']
FileUtils.mkdir_p(workspaces)
expect(FastlaneCore::Project).to receive(:choose).and_return(workspaces.last)
expect(FastlaneCore::Project).not_to(receive(:select_project))
config = FastlaneCore::Configuration.new(options, {})
FastlaneCore::Project.detect_projects(config)
expect(config[:workspace]).to eq(workspaces.last)
end
end
it 'prompts to select among multiple project files' do
within_a_temp_dir do |dir|
projects = ['./Something.xcodeproj', './SomethingElse.xcodeproj']
FileUtils.mkdir_p(projects)
expect(FastlaneCore::Project).to receive(:choose).and_return(projects.last)
expect(FastlaneCore::Project).not_to(receive(:select_project))
config = FastlaneCore::Configuration.new(options, {})
FastlaneCore::Project.detect_projects(config)
expect(config[:project]).to eq(projects.last)
end
end
it 'asks the user to specify a project when none are found' do
within_a_temp_dir do |dir|
project = './subdir/Something.xcodeproj'
FileUtils.mkdir_p(project)
expect(FastlaneCore::UI).to receive(:input).and_return(project)
config = FastlaneCore::Configuration.new(options, {})
FastlaneCore::Project.detect_projects(config)
expect(config[:project]).to eq(project)
end
end
it 'asks the user to specify a workspace when none are found' do
within_a_temp_dir do |dir|
workspace = './subdir/Something.xcworkspace'
FileUtils.mkdir_p(workspace)
expect(FastlaneCore::UI).to receive(:input).and_return(workspace)
config = FastlaneCore::Configuration.new(options, {})
FastlaneCore::Project.detect_projects(config)
expect(config[:workspace]).to eq(workspace)
end
end
it 'explains when a provided path is not found' do
within_a_temp_dir do |dir|
workspace = './subdir/Something.xcworkspace'
FileUtils.mkdir_p(workspace)
expect(FastlaneCore::UI).to receive(:input).and_return("something wrong")
expect(FastlaneCore::UI).to receive(:error).with(/Couldn't find/)
expect(FastlaneCore::UI).to receive(:input).and_return(workspace)
config = FastlaneCore::Configuration.new(options, {})
FastlaneCore::Project.detect_projects(config)
expect(config[:workspace]).to eq(workspace)
end
end
it 'explains when a provided path is not valid' do
within_a_temp_dir do |dir|
workspace = './subdir/Something.xcworkspace'
FileUtils.mkdir_p(workspace)
FileUtils.mkdir_p('other-directory')
expect(FastlaneCore::UI).to receive(:input).and_return('other-directory')
expect(FastlaneCore::UI).to receive(:error).with(/Path must end with/)
expect(FastlaneCore::UI).to receive(:input).and_return(workspace)
config = FastlaneCore::Configuration.new(options, {})
FastlaneCore::Project.detect_projects(config)
expect(config[:workspace]).to eq(workspace)
end
end
end
it "raises an exception if path was not found" do
tmp_path = Dir.mktmpdir
path = "#{tmp_path}/notHere123"
expect do
FastlaneCore::Project.new(project: path)
end.to raise_error("Could not find project at path '#{path}'")
end
describe "Valid Standard Project" do
before do
options = { project: "./fastlane_core/spec/fixtures/projects/Example.xcodeproj" }
@project = FastlaneCore::Project.new(options, xcodebuild_list_silent: true, xcodebuild_suppress_stderr: true)
end
it "#path" do
expect(@project.path).to eq(File.expand_path("./fastlane_core/spec/fixtures/projects/Example.xcodeproj"))
end
it "#is_workspace" do
expect(@project.is_workspace).to eq(false)
end
it "#workspace" do
expect(@project.workspace).to be_nil
end
it "#project" do
expect(@project.project).to_not(be_nil)
end
it "#project_name" do
expect(@project.project_name).to eq("Example")
end
it "#schemes returns all available schemes" do
expect(@project.schemes).to eq(["Example"])
end
it "#configurations returns all available configurations" do
expect(@project.configurations).to eq(["Debug", "Release", "SpecialConfiguration"])
end
it "#app_name", requires_xcode: true do
expect(@project.app_name).to eq("ExampleProductName")
end
it "#mac?", requires_xcode: true do
expect(@project.mac?).to eq(false)
end
it "#ios?", requires_xcode: true do
expect(@project.ios?).to eq(true)
end
it "#tvos?", requires_xcode: true do
expect(@project.tvos?).to eq(false)
end
end
describe "Valid CocoaPods Project" do
before do
options = {
workspace: "./fastlane_core/spec/fixtures/projects/cocoapods/Example.xcworkspace",
scheme: "Example"
}
@workspace = FastlaneCore::Project.new(options, xcodebuild_list_silent: true, xcodebuild_suppress_stderr: true)
end
it "#schemes returns all schemes" do
expect(@workspace.schemes).to eq(["Example"])
end
it "#schemes returns all configurations" do
expect(@workspace.configurations).to eq([])
end
end
describe "Mac Project" do
before do
options = { project: "./fastlane_core/spec/fixtures/projects/Mac.xcodeproj" }
@project = FastlaneCore::Project.new(options, xcodebuild_list_silent: true, xcodebuild_suppress_stderr: true)
end
it "#mac?", requires_xcode: true do
expect(@project.mac?).to eq(true)
end
it "#ios?", requires_xcode: true do
expect(@project.ios?).to eq(false)
end
it "#tvos?", requires_xcode: true do
expect(@project.tvos?).to eq(false)
end
it "schemes", requires_xcodebuild: true do
expect(@project.schemes).to eq(["Mac"])
end
end
describe "TVOS Project" do
before do
options = { project: "./fastlane_core/spec/fixtures/projects/ExampleTVOS.xcodeproj" }
@project = FastlaneCore::Project.new(options, xcodebuild_list_silent: true, xcodebuild_suppress_stderr: true)
end
it "#mac?", requires_xcode: true do
expect(@project.mac?).to eq(false)
end
it "#ios?", requires_xcode: true do
expect(@project.ios?).to eq(false)
end
it "#tvos?", requires_xcode: true do
expect(@project.tvos?).to eq(true)
end
it "schemes", requires_xcodebuild: true do
expect(@project.schemes).to eq(["ExampleTVOS"])
end
end
describe "Cross-Platform Project" do
before do
options = { project: "./fastlane_core/spec/fixtures/projects/Cross-Platform.xcodeproj" }
@project = FastlaneCore::Project.new(options, xcodebuild_list_silent: true, xcodebuild_suppress_stderr: true)
end
it "supported_platforms", requires_xcode: true do
expect(@project.supported_platforms).to eq([:macOS, :iOS, :tvOS, :watchOS])
end
it "#mac?", requires_xcode: true do
expect(@project.mac?).to eq(true)
end
it "#ios?", requires_xcode: true do
expect(@project.ios?).to eq(true)
end
it "#tvos?", requires_xcode: true do
expect(@project.tvos?).to eq(true)
end
it "schemes", requires_xcodebuild: true do
expect(@project.schemes).to eq(["CrossPlatformFramework"])
end
end
describe "Valid Workspace with workspace contained schemes" do
before do
options = {
workspace: "./fastlane_core/spec/fixtures/projects/workspace_schemes/WorkspaceSchemes.xcworkspace",
scheme: "WorkspaceSchemesScheme"
}
@workspace = FastlaneCore::Project.new(options, xcodebuild_list_silent: true, xcodebuild_suppress_stderr: true)
end
it "#schemes returns all schemes" do
expect(@workspace.schemes).to eq(["WorkspaceSchemesFramework", "WorkspaceSchemesApp", "WorkspaceSchemesScheme"])
end
it "#schemes returns all configurations" do
expect(@workspace.configurations).to eq([])
end
end
describe "build_settings() can handle empty lines" do
it "SUPPORTED_PLATFORMS should be iphonesimulator iphoneos on Xcode >= 8.3" do
options = { project: "./fastlane_core/spec/fixtures/projects/Example.xcodeproj" }
@project = FastlaneCore::Project.new(options, xcodebuild_list_silent: true, xcodebuild_suppress_stderr: true)
expect(FastlaneCore::Helper).to receive(:xcode_at_least?).and_return(true)
command = "xcodebuild -showBuildSettings -project ./fastlane_core/spec/fixtures/projects/Example.xcodeproj 2> /dev/null"
expect(FastlaneCore::Project).to receive(:run_command).with(command.to_s, { timeout: 3, retries: 3, print: false }).and_return(File.read("./fastlane_core/spec/fixtures/projects/build_settings_with_toolchains"))
expect(@project.build_settings(key: "SUPPORTED_PLATFORMS")).to eq("iphonesimulator iphoneos")
end
it "SUPPORTED_PLATFORMS should be iphonesimulator iphoneos on Xcode < 8.3" do
options = { project: "./fastlane_core/spec/fixtures/projects/Example.xcodeproj" }
@project = FastlaneCore::Project.new(options, xcodebuild_list_silent: true, xcodebuild_suppress_stderr: true)
expect(FastlaneCore::Helper).to receive(:xcode_at_least?).and_return(false)
command = "xcodebuild clean -showBuildSettings -project ./fastlane_core/spec/fixtures/projects/Example.xcodeproj 2> /dev/null"
expect(FastlaneCore::Project).to receive(:run_command).with(command.to_s, { timeout: 3, retries: 3, print: false }).and_return(File.read("./fastlane_core/spec/fixtures/projects/build_settings_with_toolchains"))
expect(@project.build_settings(key: "SUPPORTED_PLATFORMS")).to eq("iphonesimulator iphoneos")
end
end
describe "Build Settings with default configuration" do
before do
options = { project: "./fastlane_core/spec/fixtures/projects/Example.xcodeproj" }
@project = FastlaneCore::Project.new(options, xcodebuild_list_silent: true, xcodebuild_suppress_stderr: true)
end
it "IPHONEOS_DEPLOYMENT_TARGET should be 9.0", requires_xcode: true do
expect(@project.build_settings(key: "IPHONEOS_DEPLOYMENT_TARGET")).to eq("9.0")
end
it "PRODUCT_BUNDLE_IDENTIFIER should be tools.fastlane.app", requires_xcode: true do
expect(@project.build_settings(key: "PRODUCT_BUNDLE_IDENTIFIER")).to eq("tools.fastlane.app")
end
end
describe "Build Settings with specific configuration" do
before do
options = {
project: "./fastlane_core/spec/fixtures/projects/Example.xcodeproj",
configuration: "SpecialConfiguration"
}
@project = FastlaneCore::Project.new(options, xcodebuild_list_silent: true, xcodebuild_suppress_stderr: true)
end
it "IPHONEOS_DEPLOYMENT_TARGET should be 9.0", requires_xcode: true do
expect(@project.build_settings(key: "IPHONEOS_DEPLOYMENT_TARGET")).to eq("9.0")
end
it "PRODUCT_BUNDLE_IDENTIFIER should be tools.fastlane.app.special", requires_xcode: true do
expect(@project.build_settings(key: "PRODUCT_BUNDLE_IDENTIFIER")).to eq("tools.fastlane.app.special")
end
end
describe 'Project.xcode_build_settings_timeout' do
before do
ENV['FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT'] = nil
end
it "returns default value" do
expect(FastlaneCore::Project.xcode_build_settings_timeout).to eq(3)
end
it "returns specified value" do
ENV['FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT'] = '5'
expect(FastlaneCore::Project.xcode_build_settings_timeout).to eq(5)
end
it "returns 0 if empty" do
ENV['FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT'] = ''
expect(FastlaneCore::Project.xcode_build_settings_timeout).to eq(0)
end
it "returns 0 if garbage" do
ENV['FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT'] = 'hiho'
expect(FastlaneCore::Project.xcode_build_settings_timeout).to eq(0)
end
end
describe 'Project.xcode_build_settings_retries' do
before do
ENV['FASTLANE_XCODEBUILD_SETTINGS_RETRIES'] = nil
end
it "returns default value" do
expect(FastlaneCore::Project.xcode_build_settings_retries).to eq(3)
end
it "returns specified value" do
ENV['FASTLANE_XCODEBUILD_SETTINGS_RETRIES'] = '5'
expect(FastlaneCore::Project.xcode_build_settings_retries).to eq(5)
end
it "returns 0 if empty" do
ENV['FASTLANE_XCODEBUILD_SETTINGS_RETRIES'] = ''
expect(FastlaneCore::Project.xcode_build_settings_retries).to eq(0)
end
it "returns 0 if garbage" do
ENV['FASTLANE_XCODEBUILD_SETTINGS_RETRIES'] = 'hiho'
expect(FastlaneCore::Project.xcode_build_settings_retries).to eq(0)
end
end
describe "Project.run_command" do
def count_processes(text)
`ps -aef | grep #{text} | grep -v grep | wc -l`.to_i
end
it "runs simple commands" do
cmd = 'echo HO' # note: this command is deliberately not using `"` around `HO` as `echo` would echo those back on Windows
expect(FastlaneCore::Project.run_command(cmd)).to eq("HO\n")
end
it "runs more complicated commands" do
cmd = "ruby -e 'sleep 0.1; puts \"HI\"'"
expect(FastlaneCore::Project.run_command(cmd)).to eq("HI\n")
end
it "should timeouts and kills" do
text = "FOOBAR" # random text
count = count_processes(text)
cmd = "ruby -e 'sleep 3; puts \"#{text}\"'"
expect do
FastlaneCore::Project.run_command(cmd, timeout: 1)
end.to raise_error(Timeout::Error)
# on mac this before only partially works as expected
if FastlaneCore::Helper.mac?
# this shows the current implementation issue
# Timeout doesn't kill the running process
# i.e. see fastlane/fastlane_core#102
expect(count_processes(text)).to eq(count + 1)
sleep(5)
expect(count_processes(text)).to eq(count)
# you would be expected to be able to see the number of processes go back to count right away.
end
end
it "retries and kills" do
text = "NEEDSRETRY"
cmd = "ruby -e 'sleep 3; puts \"#{text}\"'"
expect(FastlaneCore::Project).to receive(:`).and_call_original.exactly(4).times
expect do
FastlaneCore::Project.run_command(cmd, timeout: 0.2, retries: 3)
end.to raise_error(Timeout::Error)
end
end
describe 'xcodebuild_suppress_stderr option', requires_xcode: true do
it 'generates an xcodebuild -showBuildSettings command without stderr redirection by default' do
project = FastlaneCore::Project.new({ project: "./fastlane_core/spec/fixtures/projects/Example.xcodeproj" })
expect(project.build_xcodebuild_showbuildsettings_command).not_to(match(%r{2> /dev/null}))
end
it 'generates an xcodebuild -showBuildSettings command that redirects stderr to /dev/null', requires_xcode: true do
project = FastlaneCore::Project.new(
{ project: "./fastlane_core/spec/fixtures/projects/Example.xcodeproj" },
xcodebuild_suppress_stderr: true
)
expect(project.build_xcodebuild_showbuildsettings_command).to match(%r{2> /dev/null})
end
end
describe 'xcodebuild_xcconfig option', requires_xcode: true do
it 'generates an xcodebuild -showBuildSettings command without xcconfig by default' do
project = FastlaneCore::Project.new({ project: "./fastlane_core/spec/fixtures/projects/Example.xcodeproj" })
command = "xcodebuild -showBuildSettings -project ./fastlane_core/spec/fixtures/projects/Example.xcodeproj"
expect(project.build_xcodebuild_showbuildsettings_command).to eq(command)
end
it 'generates an xcodebuild -showBuildSettings command that includes xcconfig if provided in options', requires_xcode: true do
project = FastlaneCore::Project.new({
project: "./fastlane_core/spec/fixtures/projects/Example.xcodeproj",
xcconfig: "/path/to/some.xcconfig"
})
command = "xcodebuild -showBuildSettings -project ./fastlane_core/spec/fixtures/projects/Example.xcodeproj -xcconfig /path/to/some.xcconfig"
expect(project.build_xcodebuild_showbuildsettings_command).to eq(command)
end
end
describe "#project_paths" do
it "works with basic projects" do
project = FastlaneCore::Project.new({
project: "gym/lib"
})
expect(project.project_paths).to be_an(Array)
expect(project.project_paths).to eq([File.expand_path("gym/lib")])
end
it "works with workspaces" do
workspace_path = "gym/spec/fixtures/projects/cocoapods/Example.xcworkspace"
project = FastlaneCore::Project.new({
workspace: workspace_path
})
expect(project.project_paths).to eq([
File.expand_path(workspace_path.gsub("xcworkspace", "xcodeproj")) # this should point to the included Xcode project
])
end
end
end
end
| 38.256214 | 218 | 0.659936 |
6a6429246d8fdfe517eb53093004ec4527e7b02c | 185 | class RemoveIndexOnPostIdInTopics < ActiveRecord::Migration[6.0]
disable_ddl_transaction!
def change
remove_index :topics, column: :post_id, algorithm: :concurrently
end
end
| 23.125 | 68 | 0.783784 |
39ca9f4ace5e178e60271f244844d59eba595410 | 1,463 | require 'spec_helper'
describe Breathing do
it 'has a version number' do
expect(Breathing::VERSION).not_to be nil
end
describe 'change_logs' do
before { Breathing::Installer.new.install }
after do
Breathing::Installer.new.uninstall if ActiveRecord::Base.connection.adapter_name == "Mysql2"
end
it do
expect(Breathing::ChangeLog.count).to eq(0)
# INSERT
user = User.create!(name: 'a', age: 20)
expect(Breathing::ChangeLog.count).to eq(1)
log = Breathing::ChangeLog.where(table_name: user.class.table_name, transaction_id: user.id).last
expect(log.before_data).to eq({})
expect(log.after_data['name']).to eq('a')
expect(log.after_data['age']).to eq(20)
# UPDATE
user.update!(age: 21)
expect(Breathing::ChangeLog.count).to eq(2)
log = Breathing::ChangeLog.where(table_name: user.class.table_name, transaction_id: user.id).last
expect(log.before_data['age']).to eq(20)
expect(log.after_data['age']).to eq(21)
expect(log.before_data['name']).to eq(log.after_data['name'])
expect(log.changed_attribute_columns).to eq(%w[age updated_at])
# DELETE
user.destroy!
expect(Breathing::ChangeLog.count).to eq(3)
log = Breathing::ChangeLog.where(table_name: user.class.table_name, transaction_id: user.id).last
expect(log.before_data['name']).to eq('a')
expect(log.after_data).to eq({})
end
end
end
| 31.804348 | 103 | 0.666439 |
2615bb1379bcfc45b1859315fd351ad32bedbd25 | 149 | $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'multiset'
| 29.8 | 67 | 0.724832 |
e9b27b1185b915ecbbd6a69a5c084d271534129e | 1,107 | require 'formula'
class Goffice < Formula
homepage 'http://projects.gnome.org/gnumeric/'
url 'http://ftp.gnome.org/pub/GNOME/sources/goffice/0.8/goffice-0.8.17.tar.bz2'
sha256 'dd8caef5fefffbc53938fa619de9f58e7c4dc71a1803de134065d42138a68c06'
depends_on 'pkg-config' => :build
depends_on 'intltool' => :build
depends_on 'gettext'
depends_on 'libgsf'
depends_on 'gtk+'
depends_on 'pcre'
depends_on :x11
# Fix for goffice trying to use a retired pcre api. Reported/source = Macports
# https://github.com/mxcl/homebrew/issues/15171
def patches
DATA
end
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make install"
end
end
__END__
--- a/goffice/utils/regutf8.c 2009-09-05 16:52:09.000000000 -0700
+++ b/goffice/utils/regutf8.c 2012-09-28 20:53:51.000000000 -0700
@@ -155,7 +155,7 @@
default: return GO_REG_BADPAT;
}
} else {
- gor->re_nsub = pcre_info (r, NULL, NULL);
+ gor->re_nsub = pcre_fullinfo (r, NULL, 0, NULL);
gor->nosub = (cflags & GO_REG_NOSUB) != 0;
return 0;
}
| 27 | 81 | 0.68112 |
281c2da6ac86e9a3f70f32f6bdb9fa5311af32db | 2,305 | DEFAULT_RAILS_DIR = File.join('..', 'rails')
DEFAULT_ADAPTERS = %w(MySQL SQLite3 Postgres)
namespace :rails do
namespace :test do
task :all do
driver = ENV['DRIVER'] || ENV['ADAPTER']
raise "need a DRIVER (DRIVER=mysql)" unless driver
rails_dir = _rails_dir
ENV['ARCONFIG'] = File.join(_ar_jdbc_dir, 'test', 'rails', 'config.yml')
Dir.chdir(File.join(rails_dir, 'activerecord')) do
sh FileUtils::RUBY, '-S', 'rake',
"RUBYLIB=#{_ruby_lib(rails_dir, driver)}",
_target(driver)
end
end
DEFAULT_ADAPTERS.each do |adapter|
desc "Run Rails ActiveRecord tests with #{adapter} (JDBC)"
task adapter.downcase do
ENV['ADAPTER'] = adapter
Rake::Task['rails:test:all'].invoke
end
namespace adapter.downcase do
desc "Runs Rails ActiveRecord base_test.rb with #{adapter}"
task "base_test" do
ENV['TEST'] ||= "test/cases/base_test.rb"
ENV['ADAPTER'] = adapter
Rake::Task['rails:test:all'].invoke
end
end
end
private
def _ar_jdbc_dir
@ar_jdbc_dir ||= File.expand_path('..', File.dirname(__FILE__))
end
def _rails_dir
rails_dir = ENV['RAILS'] || DEFAULT_RAILS_DIR
unless File.directory? rails_dir
raise "can't find RAILS source '#{rails_dir}' (maybe set ENV['RAILS'])"
end
rails_dir = File.join(rails_dir, '..') if rails_dir =~ /activerecord$/
rails_dir
end
def _ruby_lib(rails_dir, driver)
ar_jdbc_dir = _ar_jdbc_dir
if driver =~ /postgres/i
adapter, driver = 'postgresql', 'postgres'
else
adapter = driver.downcase
driver = adapter
end
[File.join(ar_jdbc_dir, 'lib'),
File.join(ar_jdbc_dir, 'test', 'rails'),
File.join(ar_jdbc_dir, "jdbc-#{driver}", 'lib'),
File.join(ar_jdbc_dir, "activerecord-jdbc#{adapter}-adapter", 'lib'),
File.expand_path('activesupport/lib', rails_dir),
File.expand_path('activemodel/lib', rails_dir),
File.expand_path('activerecord/lib', rails_dir)
].join(':')
end
def _target(name)
case name
when /postgres/i
'test_postgresql'
else
"test_jdbc#{name.downcase}"
end
end
end
end
| 28.45679 | 79 | 0.606074 |
e920ac13b1da834f841da6605e5ebf6ee3a65d95 | 567 | require_dependency 'fieri/application_controller'
module Fieri
class JobsController < ApplicationController
def create
MetricsRunner.perform_async(job_params)
render json: { status: 'ok' }.to_json
rescue ActionController::ParameterMissing => e
render status: 400, json: { status: 'error',
message: e.message }
end
private
def job_params
[:cookbook_name, :cookbook_version, :cookbook_artifact_url].each do |param|
params.require(param)
end
params
end
end
end
| 24.652174 | 81 | 0.652557 |
d5a6bd061473f8915a09a60b738c99665538f588 | 6,297 | require 'spec_helper'
require 'john-hancock/request_proxy/uri'
module Devise::Models
describe JohnHancockAuthenticatable do
before(:each) do
@model_class = Devise::Mock::ApiKey
@model = @model_class.new
end
def signature(uri)
request = Rack::Request.new(Rack::MockRequest.env_for(uri))
proxy = JohnHancock::RequestProxy.proxy(request)
JohnHancock::Signature::DeviseTestSignature.new(proxy)
end
it "adds config methods to model class" do
@model_class.should respond_to('signature_authenticatable')
@model_class.should respond_to('signature_algorithm')
@model_class.should respond_to('signature_algorithm_options')
@model_class.should respond_to('signature_validate_signature')
@model_class.should respond_to('signature_validate_timestamp')
@model_class.should respond_to('signature_timestamp_offset')
end
it "adds class methods to model class" do
@model_class.should respond_to('signature_authenticatable?')
@model_class.should respond_to('find_for_signature_authentication')
end
it "adds instance methods to model" do
@model.should respond_to('valid_signature?')
@model.should respond_to('configure_signature!')
@model.should respond_to('after_signature_authentication')
end
describe 'signature_authenticatable?' do
it "returns true when strategy is in an array of strategies" do
stub(Devise).signature_authenticatable{[:john_hancock, :foo_bar]}
@model_class.should be_signature_authenticatable(:john_hancock)
end
it "returns true for a globally true configuration" do
stub(Devise).signature_authenticatable{true}
@model_class.should be_signature_authenticatable(:john_hancock)
end
it "returns true for a globally false configuration" do
stub(Devise).signature_authenticatable{false}
@model_class.should_not be_signature_authenticatable(:john_hancock)
end
end
describe 'signature' do
before(:each) do
@request = Rack::Request.new(Rack::MockRequest.env_for('http://example.com/'))
end
it "creates a new signature" do
@model_class.signature(@request).should be_a(JohnHancock::Signature::Base)
end
it "uses the configured signature algorithm" do
stub(Devise).signature_algorithm{:devise_test_signature}
mock(JohnHancock::Signature).build.with_any_args do |*args|
args[0].should == :devise_test_signature
end
@model_class.signature(@request)
end
it "overrides configured signature options with passed options" do
stub(Devise).signature_algorithm_options{{:foo => 'bar'}}
mock(JohnHancock::Signature).build.with_any_args do |*args|
args[2].should == {:bar => 'foo'}
end
@model_class.signature(@request, {:bar => 'foo'})
end
it "uses the configured signature options if none are passed" do
stub(Devise).signature_algorithm_options{{:foo => 'bar'}}
mock(JohnHancock::Signature).build.with_any_args do |*args|
args[2].should == {:foo => 'bar'}
end
@model_class.signature(@request)
end
end
describe 'configure_signature!' do
it "sets the secret" do
s = signature("http://example.com/foo/bar")
@model.secret = 'My new secret'
@model.configure_signature!(s)
s.secret.should == 'My new secret'
end
it "sets the valid timestamp range" do
now = Time.now.to_i
stub(Devise::Mock::ApiKey).signature_timestamp_offset{(-3..3)}
s = signature("http://example.com/foo/bar")
@model.configure_signature!(s, now)
s.valid_timestamp_range.should == ((now-3)..(now+3))
end
end
describe 'valid_signature?' do
it "returns true for a valid signature" do
t = Time.now.to_i
s = signature("http://example.com/categories/search?foo=bar&test=123&signature=foobar×tamp=#{t}")
@model.configure_signature!(s)
@model.valid_signature?(s).should == true
end
it "returns :invalid for invalid signature" do
t = Time.now.to_i
s = signature("http://example.com/categories/search?foo=bar&test=123&signature=fooBar×tamp=#{t}")
@model.configure_signature!(s)
@model.valid_signature?(s).should == :invalid
end
it "returns :expired for invalid timestamp" do
t = Time.now.to_i - 86400
s = signature("http://example.com/categories/search?foo=bar&test=123&signature=foobar×tamp=#{t}")
@model.configure_signature!(s)
@model.valid_signature?(s).should == :expired
end
it "does not validate signature if signature_validate_signature=false" do
stub(Devise::Mock::ApiKey).signature_validate_signature{false}
t = Time.now.to_i
s = signature("http://example.com/categories/search?foo=bar&test=123&signature=raboof×tamp=#{t}")
@model.configure_signature!(s)
@model.valid_signature?(s).should == true
end
it "does not validate timestamp if signature_validate_timestamp=false" do
stub(Devise::Mock::ApiKey).signature_validate_timestamp{false}
t = Time.now.to_i - 86400
s = signature("http://example.com/categories/search?foo=bar&test=123&signature=foobar×tamp=#{t}")
@model.configure_signature!(s)
@model.valid_signature?(s).should == true
end
end
describe "signature_timestamp_offset" do
it "accepts an integer offset" do
stub(Devise::Mock::ApiKey).signature_timestamp_offset{86500}
t = Time.now.to_i - 86400
s = signature("http://example.com/categories/search?foo=bar&test=123&signature=foobar×tamp=#{t}")
@model.configure_signature!(s)
@model.valid_signature?(s).should == true
end
it "accepts a range offset" do
stub(Devise::Mock::ApiKey).signature_timestamp_offset{(-3..3)}
t = Time.now.to_i + 5
s = signature("http://example.com/categories/search?foo=bar&test=123&signature=foobar×tamp=#{t}")
@model.configure_signature!(s)
@model.valid_signature?(s).should == :expired
end
end
end
end
| 36.398844 | 110 | 0.67016 |
11151d9486099ffb4c1557f3cc46e256a0e6ad7e | 313 | class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :meetings_attended
t.string :current_projects
t.string :expenditures
t.string :other
t.belongs_to :user
t.timestamps null: false
end
add_index :posts, :user_id
end
end
| 19.5625 | 43 | 0.667732 |
336b2902b556583111a0aea2cfb2a0d95d8ca96b | 7,702 | # frozen_string_literal: true
require 'test_helper'
class TransactionControllerTest < ActionDispatch::IntegrationTest
test 'create new transaction should work' do
stub_request(:any, %r{transactions/watch})
.to_return(body: {
result: {
seen: [attributes_for(:transaction)],
confirmed: [attributes_for(:transaction)]
}
}.to_json)
_user, auth_headers, _key = create_auth_user
params = attributes_for(:transaction)
post transactions_path,
params: params,
headers: auth_headers
assert_response :success,
'should work'
assert_match 'title', @response.body,
'response should contain ok status'
claim_attrs = attributes_for(:claim_result_transaction)
post transactions_path,
params: claim_attrs,
headers: auth_headers
assert_response :success,
'should work with claim type transaction'
claim_data = JSON.parse(@response.body)['result']
assert_equal claim_attrs[:type], claim_data['type'],
'type should be the same'
assert_equal claim_attrs[:project], claim_data['project'],
'project should be the same'
post transactions_path,
params: params,
headers: auth_headers
assert_response :success,
'should fail on retry'
assert_match 'error', @response.body,
'response should contain errors'
end
test 'create new transaction can fail safely' do
stub_request(:any, /transactions/)
.to_return(body: {
result: {
seen: [attributes_for(:transaction)],
confirmed: [attributes_for(:transaction)]
}
}.to_json)
_user, auth_headers, _key = create_auth_user
params = attributes_for(:transaction)
post transactions_path,
params: params
assert_response :unauthorized,
'should fail on without authorization'
post transactions_path,
headers: auth_headers
assert_response :success,
'should fail on with empty data'
assert_match 'error', @response.body,
'response should contain validation errors'
end
test 'list transaction should work' do
user, auth_headers, _key = create_auth_user
15.times do
create(:transaction, user: user)
end
3.times do
create(:transaction_claim_result, user: user)
end
get transactions_path,
headers: auth_headers
assert_response :success,
'should work'
assert_match 'title', @response.body,
'response should contain ok status'
assert_equal 10, JSON.parse(@response.body)['result'].size,
'should have 10 transactions'
get transactions_path,
params: { status: 'pending' },
headers: auth_headers
assert_response :success,
'pending status should work'
assert_equal 3, JSON.parse(@response.body)['result'].size,
'should have 3 pending transactions'
get transactions_path,
params: { all: '' },
headers: auth_headers
assert_response :success,
'should work with pagination disabled'
assert_match 'title', @response.body,
'response should contain results'
assert_equal 18, JSON.parse(@response.body)['result'].size,
'should have 18 overall transactions'
get transactions_path
assert_response :unauthorized,
'should fail on without authorization'
end
test 'list transactions should be paginated' do
user, auth_headers, _key = create_auth_user
create_list(:transaction, Random.rand(10..20), user: user)
Random.rand(5..10).times do
page = Random.rand(1..20)
per_page = Random.rand(1..50)
get "#{transactions_path}?page=#{page}&per_page=#{per_page}",
headers: auth_headers
assert_response :success,
'should work'
result = JSON.parse(@response.body).fetch('result', [])
items = user.transactions.page(page).per(per_page)
assert_equal items.size, result.size,
'should paginate correctly'
end
end
test 'confirm transactions should work' do
successful_transactions = create_list(:transaction, 10)
failed_transactions = create_list(:transaction, 10)
path = transactions_update_path('confirmed')
payload = { success: successful_transactions, failed: failed_transactions }
assert_self_nonce_increased do
info_put path,
payload: payload
end
assert_response :success,
'should work'
assert_match 'confirmed', @response.body,
'response should be ok'
Transaction.where(id: successful_transactions.map(&:id)).each do |txn|
assert_equal 'confirmed', txn.status,
'successful transactions are confirmed'
end
Transaction.where(id: failed_transactions.map(&:id)).each do |txn|
assert_equal 'failed', txn.status,
'failed transactions are failure'
end
put path,
params: { payload: payload }.to_json
assert_response :forbidden,
'should fail without a signature'
info_put transactions_update_path('invalid_action'),
payload: {}
assert_response :unprocessable_entity,
'should fail if the action is incorrect'
end
test 'latest transactions should work' do
transactions = (1..10).map do |_|
create(:transaction)
end
block_number = generate(:block_number)
payload = {
transactions: transactions,
block_number: block_number
}
path = transactions_update_path('seen')
assert_self_nonce_increased do
info_put path,
payload: payload
end
assert_response :success,
'should work'
assert_match 'seen', @response.body,
'response should say ok'
Transaction.all.each do |txn|
assert_equal 'seen', txn.status,
'transactions should be seen'
assert_equal block_number, txn.block_number,
'transactions should have the correct block number'
end
put path,
params: { payload: payload }.to_json
assert_response :forbidden,
'should fail without a signature'
info_put transactions_update_path('invalid_action'),
payload: payload
assert_response :unprocessable_entity,
'should fail if the action is incorrect'
end
test 'find transaction should work' do
transaction = create(:transaction)
get transaction_path,
params: { txhash: transaction.txhash }
assert_response :success,
'should work'
assert_match 'id', @response.body,
'response should give the transaction'
get transaction_path,
params: { txhash: 'NON_EXISTENT_HASH' }
assert_response :success,
'should fail with invalid hash'
assert_match 'error', @response.body,
'response should give transaction missing error'
end
test 'test server should work' do
payload = generate(:txhash)
assert_self_nonce_increased do
info_get transactions_ping_path,
payload: payload
end
assert_response :success,
'should work'
assert_match 'ok', @response.body,
'response should say ok'
get transactions_ping_path
assert_response :forbidden,
'should fail without authorization'
end
end
| 28.316176 | 79 | 0.62724 |
1abb6ce4b48a8981c8943278cf8f927d06c3d4e4 | 1,330 | module Xremap
module KeyExpression
class << self
# @param [String] exp
# @return [Xremap::Config::Key] key
def compile(exp)
keyexp, modifiers = split_into_key_and_mods(exp)
Config::Key.new(to_keysym(keyexp), modifier_mask(modifiers))
end
private
def split_into_key_and_mods(exp)
modifiers = []
while exp.match(/\A(?<modifier>(C|Ctrl|M|Alt|Shift|Super|Hyper))-/)
modifier = Regexp.last_match[:modifier]
modifiers << modifier
exp = exp.sub(/\A#{modifier}-/, '')
end
[exp, modifiers]
end
def modifier_mask(modifiers)
mask = X11::NoModifier
modifiers.each do |modifier|
case modifier
when 'C', 'Ctrl'
mask |= X11::ControlMask
when 'Alt'
mask |= X11::Mod1Mask
when 'M'
mask |= X11::Mod2Mask
when 'Super'
mask |= X11::Mod3Mask
when 'Hyper'
mask |= X11::Mod4Mask
when 'Shift'
mask |= X11::ShiftMask
end
end
mask
end
def to_keysym(keyexp)
if keyexp.start_with?('XF86XK_')
X11.const_get(keyexp)
else
X11.const_get("XK_#{keyexp}")
end
end
end
end
end
| 24.62963 | 75 | 0.521053 |
117e55bdfe5dc457973e8f3bec0e347fe86d766f | 623 | module Fog
module Parsers
module DNS
module Bluebox
class GetZones < Fog::Parsers::Base
def reset
@zone = {}
@response = { 'zones' => [] }
end
def end_element(name)
case name
when 'serial', 'ttl', 'retry', 'expires', 'record-count', 'refresh', 'minimum'
@zone[name] = value.to_i
when 'name', 'id'
@zone[name] = value
when 'record'
@response['zones'] << @zone
@zone = {}
end
end
end
end
end
end
end
| 20.096774 | 90 | 0.428571 |
1ded889d2d158454a1427dda2288a3e8f6dc85d9 | 14,110 | require_relative '../../../shared/spec_helper.rb'
describe 'tomcat/init.sls' do
case os[:family]
when 'debian'
pkgs_installed = %w(tomcat8 haveged tomcat8-admin)
pkgs_not_installed = []
main_config = '/etc/default/tomcat8'
catalina_logfile = '/var/log/tomcat8/catalina.out'
service = 'tomcat8'
service_running: False
when 'redhat'
pkgs_installed = %w(tomcat tomcat-admin-webapps)
pkgs_not_installed = %w(haveged)
main_config = '/etc/sysconfig/tomcat'
cur_date = Time.now.strftime("%Y-%m-%d")
catalina_logfile = "/var/log/tomcat/catalina.#{cur_date}.log"
service = 'tomcat'
service_running: False
when 'arch'
pkgs_installed = %w(tomcat8 haveged)
pkgs_not_installed = []
main_config = '/usr/lib/systemd/system/tomcat8.service'
catalina_logfile = '/var/log/tomcat/catalina.out'
service = 'tomcat8'
service_running: False
when 'ubuntu'
case os[:release]
when '14.04'
pkgs_installed = %w(tomcat7 haveged tomcat7-admin)
pkgs_not_installed = []
main_config = '/etc/default/tomcat7'
catalina_logfile = '/var/log/tomcat7/catalina.out'
service = 'tomcat7'
service_running: False
when '16.04'
pkgs_installed = %w(tomcat8 haveged tomcat8-admin)
pkgs_not_installed = []
main_config = '/etc/default/tomcat8'
catalina_logfile = '/var/log/tomcat8/catalina.out'
service = 'tomcat8'
service_running: False
when '18.04'
pkgs_installed = %w(tomcat8 haveged tomcat8-admin)
pkgs_not_installed = []
main_config = '/etc/default/tomcat8'
catalina_logfile = '/var/log/tomcat8/catalina.out'
service = 'tomcat'
service_running: False
end
end
pkgs_installed.each do |p|
describe package(p) do
it { should be_installed }
end
end
pkgs_not_installed.each do |p|
describe package(p) do
it { should_not be_installed }
end
end
#skip service check because tomcat needs java
#describe service(service) do
# it { should be_running }
#nd
describe file(main_config) do
it { should be_file }
its(:content) { should_not match('# This file is managed by salt.') }
end
describe file(catalina_logfile) do
it { should be_file }
its(:content) { should contain('INFO: Server startup in') }
end
end
describe 'tomcat/native.sls' do
case os[:family]
when 'debian'
ver = '8'
pkgs_installed = %w(libtcnative-1)
main_config = '/etc/default/tomcat8'
server_config = '/etc/tomcat8/server.xml'
context_config = '/etc/tomcat8/context.xml'
catalina_logfile = '/var/log/tomcat8/catalina.out'
web_config = '/etc/tomcat8/web.xml'
user_config = '/etc/tomcat8/tomcat-users.xml'
username = 'saltuser1'
password = 'RfgpE2iQwD'
roles = 'manager-gui,manager-script,manager-jmx,manager-status'
service = 'tomcat8'
user = 'tomcat8'
group = 'tomcat8'
java_home = '/usr/lib/jvm/java-7-openjdk'
limits_file = '/etc/security/limits.d/tomcat8.conf'
describe command("apt install libxml2-utils") do
its(:exit_status) { should eq 0 }
end
when 'redhat'
ver = '8'
pkgs_installed = %w(tomcat-native)
main_config = '/etc/sysconfig/tomcat'
server_config = '/etc/tomcat8/server.xml'
context_config = '/etc/tomcat8/context.xml'
catalina_logfile = '/var/log/tomcat8/catalina.out'
web_config = '/etc/tomcat8/web.xml'
user_config = '/etc/tomcat8/tomcat-users.xml'
username = 'saltuser1'
password = 'RfgpE2iQwD'
roles = 'manager-gui,manager-script,manager-jmx,manager-status'
service = 'tomcat'
user = 'tomcat'
group = 'tomcat'
java_home = '/usr/lib/jvm/jre'
limits_file = '/etc/security/limits.d/tomcat7.conf'
describe command("yum install libxml2") do
its(:exit_status) { should eq 0 }
end
when 'arch'
ver = '8'
pkgs_installed = %w(tomcat-native)
main_config = '/usr/lib/systemd/system/tomcat8.service'
server_config = '/etc/tomcat8/server.xml'
context_config = '/etc/tomcat8/context.xml'
catalina_logfile = '/var/log/tomcat/catalina.out'
web_config = '/etc/tomcat8/web.xml'
user_config = '/etc/tomcat8/tomcat-users.xml'
username = 'saltuser1'
password = 'RfgpE2iQwD'
roles = 'manager-gui,manager-script,manager-jmx,manager-status'
service = 'tomcat8'
user = 'tomcat8'
group = 'tomcat8'
java_home = '/usr/lib/jvm/default-runtime'
limits_file = '/etc/security/limits.conf'
describe command("pacman -S libxml2") do
its(:exit_status) { should eq 0 }
end
when 'ubuntu'
case os[:release]
when '14.04'
ver = '7'
pkgs_installed = %w(libtcnative-1)
main_config = '/etc/default/tomcat7'
server_config = '/etc/tomcat7/server.xml'
context_config = '/etc/tomcat7/context.xml'
catalina_logfile = '/var/log/tomcat7/catalina.out'
web_config = '/etc/tomcat7/web.xml'
user_config = '/etc/tomcat7/tomcat-users.xml'
username = 'saltuser1'
password = 'RfgpE2iQwD'
roles = 'manager-gui,manager-script,manager-jmx,manager-status'
service = 'tomcat7'
user = 'tomcat7'
group = 'tomcat7'
java_home = '/usr/lib/jvm/java-7-openjdk'
limits_file = '/etc/security/limits.d/tomcat7.conf'
describe command("apt install libxml2-utils") do
its(:exit_status) { should eq 0 }
end
when '16.04'
ver = '8'
pkgs_installed = %w(libtcnative-1)
main_config = '/etc/default/tomcat8'
server_config = '/etc/tomcat8/server.xml'
context_config = '/etc/tomcat8/context.xml'
catalina_logfile = '/var/log/tomcat8/catalina.out'
web_config = '/etc/tomcat8/web.xml'
user_config = '/etc/tomcat8/tomcat-users.xml'
username = 'saltuser1'
password = 'RfgpE2iQwD'
roles = 'manager-gui,manager-script,manager-jmx,manager-status'
service = 'tomcat8'
user = 'tomcat8'
group = 'tomcat8'
java_home = '/usr/lib/jvm/java-7-openjdk'
limits_file = '/etc/security/limits.d/tomcat8.conf'
describe command("apt install libxml2-utils") do
its(:exit_status) { should eq 0 }
when '18.04'
ver = '8'
pkgs_installed = %w(libtcnative-1)
main_config = '/etc/default/tomcat8'
server_config = '/etc/tomcat8/server.xml'
context_config = '/etc/tomcat8/context.xml'
catalina_logfile = '/var/log/tomcat8/catalina.out'
web_config = '/etc/tomcat8/web.xml'
user_config = '/etc/tomcat8/tomcat-users.xml'
username = 'saltuser1'
password = 'RfgpE2iQwD'
roles = 'manager-gui,manager-script,manager-jmx,manager-status'
service = 'tomcat8'
user = 'tomcat8'
group = 'tomcat8'
java_home = '/usr/lib/jvm/java-7-openjdk'
limits_file = '/etc/security/limits.d/tomcat8.conf'
describe command("apt install libxml2-utils") do
its(:exit_status) { should eq 0 }
end
end
end
pkgs_installed.each do |p|
describe package(p) do
it { should be_installed }
end
end
#skip service check because tomcat needs java
#describe service(service) do
# it { should be_running }
#end
describe file(server_config) do
it { should be_file }
its(:content) { should contain('This file is managed/autogenerated by salt.') }
its(:content) { should contain('<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />') }
describe command("xmllint --noout #{server_config}") do
its(:exit_status) { should eq 0 }
end
end
describe file(catalina_logfile) do
it { should be_file }
its(:content) { should contain('INFO: Server startup in') }
end
end
describe 'tomcat/config.sls' do
case os[:family]
when 'debian'
ver = '8'
pkgs_installed = %w(libtcnative-1)
main_config = '/etc/default/tomcat8'
server_config = '/etc/tomcat8/server.xml'
context_config = '/etc/tomcat8/context.xml'
catalina_logfile = '/var/log/tomcat8/catalina.out'
web_config = '/etc/tomcat8/web.xml'
user_config = '/etc/tomcat8/tomcat-users.xml'
username = 'saltuser1'
password = 'RfgpE2iQwD'
roles = 'manager-gui,manager-script,manager-jmx,manager-status'
service = 'tomcat8'
user = 'tomcat8'
group = 'tomcat8'
java_home = '/usr/lib/jvm/java-7-openjdk'
limits_file = '/etc/security/limits.d/tomcat8.conf'
describe command("apt install libxml2-utils") do
its(:exit_status) { should eq 0 }
end
when 'redhat'
ver = '8'
pkgs_installed = %w(tomcat-native)
main_config = '/etc/sysconfig/tomcat'
server_config = '/etc/tomcat8/server.xml'
context_config = '/etc/tomcat8/context.xml'
catalina_logfile = '/var/log/tomcat8/catalina.out'
web_config = '/etc/tomcat8/web.xml'
user_config = '/etc/tomcat8/tomcat-users.xml'
username = 'saltuser1'
password = 'RfgpE2iQwD'
roles = 'manager-gui,manager-script,manager-jmx,manager-status'
service = 'tomcat'
user = 'tomcat'
group = 'tomcat'
java_home = '/usr/lib/jvm/jre'
limits_file = '/etc/security/limits.d/tomcat7.conf'
describe command("yum install libxml2") do
its(:exit_status) { should eq 0 }
end
when 'arch'
ver = '8'
pkgs_installed = %w(tomcat-native)
main_config = '/usr/lib/systemd/system/tomcat8.service'
server_config = '/etc/tomcat8/server.xml'
context_config = '/etc/tomcat8/context.xml'
catalina_logfile = '/var/log/tomcat/catalina.out'
web_config = '/etc/tomcat8/web.xml'
user_config = '/etc/tomcat8/tomcat-users.xml'
username = 'saltuser1'
password = 'RfgpE2iQwD'
roles = 'manager-gui,manager-script,manager-jmx,manager-status'
service = 'tomcat8'
user = 'tomcat8'
group = 'tomcat8'
java_home = '/usr/lib/jvm/default-runtime'
limits_file = '/etc/security/limits.conf'
describe command("pacman -S libxml2") do
its(:exit_status) { should eq 0 }
end
when 'ubuntu'
case os[:release]
when '14.04'
ver = '7'
pkgs_installed = %w(libtcnative-1)
main_config = '/etc/default/tomcat7'
server_config = '/etc/tomcat7/server.xml'
context_config = '/etc/tomcat7/context.xml'
catalina_logfile = '/var/log/tomcat7/catalina.out'
web_config = '/etc/tomcat7/web.xml'
user_config = '/etc/tomcat7/tomcat-users.xml'
username = 'saltuser1'
password = 'RfgpE2iQwD'
roles = 'manager-gui,manager-script,manager-jmx,manager-status'
service = 'tomcat7'
user = 'tomcat7'
group = 'tomcat7'
java_home = '/usr/lib/jvm/java-7-openjdk'
limits_file = '/etc/security/limits.d/tomcat7.conf'
describe command("apt install libxml2-utils") do
its(:exit_status) { should eq 0 }
end
when '16.04'
ver = '8'
pkgs_installed = %w(libtcnative-1)
main_config = '/etc/default/tomcat8'
server_config = '/etc/tomcat8/server.xml'
context_config = '/etc/tomcat8/context.xml'
catalina_logfile = '/var/log/tomcat8/catalina.out'
web_config = '/etc/tomcat8/web.xml'
user_config = '/etc/tomcat8/tomcat-users.xml'
username = 'saltuser1'
password = 'RfgpE2iQwD'
roles = 'manager-gui,manager-script,manager-jmx,manager-status'
service = 'tomcat8'
user = 'tomcat8'
group = 'tomcat8'
java_home = '/usr/lib/jvm/java-7-openjdk'
limits_file = '/etc/security/limits.d/tomcat8.conf'
describe command("apt install libxml2-utils") do
its(:exit_status) { should eq 0 }
end
end
end
pkgs_installed.each do |p|
describe package(p) do
it { should be_installed }
end
end
#skip service check because tomcat needs java
#describe service(service) do
# it { should be_running }
#end
describe file(main_config) do
it { should be_file }
its(:content) { should match('# This file is managed by salt.') }
case os[:family]
when 'debian', 'redhat'
its(:content) { should match(/^TOMCAT.?_USER=#{user}/) }
its(:content) { should match(/^TOMCAT.?_GROUP=#{group}/) }
its(:content) { should match(/^JAVA_OPTS=\"-Djava\.awt\.headless=true -Xmx128m -XX:MaxPermSize=256m -XX:\+UseConcMarkSweepGC -XX:\+CMSIncrementalMode -Dlog4j\.configuration=file:\/path\/to\/log4j.properties -Dlogback.configurationFile=\/path\/to\/logback.xml\"/) }
when 'arch'
its(:content) { should match(/^Environment=TOMCAT_JAVA_HOME=#{java_home}/) }
its(:content) { should match(/^Environment=\"CATALINA_OPTS=-Djava\.awt\.headless=true -Xmx128m -XX:MaxPermSize=256m -XX:\+UseConcMarkSweepGC -XX:\+CMSIncrementalMode -Dlog4j\.configuration=file:\/path\/to\/log4j.properties -Dlogback.configurationFile=\/path\/to\/logback.xml\"/) }
its(:content) { should_not match(/^TOMCAT.?_GROUP=#{group}/) }
end
end
describe file(server_config) do
it { should be_file }
its(:content) { should contain('This file is managed/autogenerated by salt.') }
its(:content) { should contain('port="8080"') }
its(:content) { should contain('protocol="HTTP/1.1"') }
its(:content) { should contain('connectionTimeout="20000"') }
its(:content) { should contain('URIEncoding="UTF-8"') }
describe command("xmllint --noout #{server_config}") do
its(:exit_status) { should eq 0 }
end
end
describe file(web_config) do
it { should be_file }
its(:content) { should contain('This file is managed/autogenerated by salt.') }
its(:content) { should contain('<filter-name>ExpiresFilter</filter-name>') }
its(:content) { should contain('2 weeks') }
describe command("xmllint --noout #{web_config}") do
its(:exit_status) { should eq 0 }
end
end
describe file(limits_file) do
it { should be_file }
its(:content) { should match(/^#{user} soft nofile 48000/) }
its(:content) { should match(/^#{user} hard nofile 64000/) }
end
describe file(catalina_logfile) do
it { should be_file }
its(:content) { should contain('INFO: Server startup in') }
end
end
| 34.498778 | 286 | 0.654571 |
1a8c756323f5d31521621199261415a9a7186a24 | 97,050 | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops
module Types
describe 'The type calculator' do
let(:calculator) { TypeCalculator.new }
def range_t(from, to)
PIntegerType.new(from, to)
end
def pattern_t(*patterns)
TypeFactory.pattern(*patterns)
end
def regexp_t(pattern)
TypeFactory.regexp(pattern)
end
def string_t(string = nil)
TypeFactory.string(string)
end
def constrained_string_t(size_type)
TypeFactory.string(size_type)
end
def callable_t(*params)
TypeFactory.callable(*params)
end
def all_callables_t
TypeFactory.all_callables
end
def enum_t(*strings)
TypeFactory.enum(*strings)
end
def variant_t(*types)
TypeFactory.variant(*types)
end
def empty_variant_t()
t = TypeFactory.variant()
# assert this to ensure we did get an empty variant (or tests may pass when not being empty)
raise 'typefactory did not return empty variant' unless t.types.empty?
t
end
def type_alias_t(name, type_string)
type_expr = Parser::EvaluatingParser.new.parse_string(type_string)
TypeFactory.type_alias(name, type_expr)
end
def type_reference_t(type_string)
TypeFactory.type_reference(type_string)
end
def integer_t
TypeFactory.integer
end
def array_t(t, s = nil)
TypeFactory.array_of(t, s)
end
def empty_array_t
empty_array = array_t(unit_t, range_t(0,0))
end
def hash_t(k,v,s = nil)
TypeFactory.hash_of(v, k, s)
end
def data_t
TypeFactory.data
end
def factory
TypeFactory
end
def collection_t(size_type = nil)
TypeFactory.collection(size_type)
end
def tuple_t(*types)
TypeFactory.tuple(types)
end
def constrained_tuple_t(size_type, *types)
TypeFactory.tuple(types, size_type)
end
def struct_t(type_hash)
TypeFactory.struct(type_hash)
end
def any_t
TypeFactory.any
end
def optional_t(t)
TypeFactory.optional(t)
end
def type_t(t)
TypeFactory.type_type(t)
end
def not_undef_t(t = nil)
TypeFactory.not_undef(t)
end
def undef_t
TypeFactory.undef
end
def unit_t
# Cannot be created via factory, the type is private to the type system
PUnitType::DEFAULT
end
def runtime_t(t, c)
TypeFactory.runtime(t, c)
end
def object_t(hash)
TypeFactory.object(hash)
end
def iterable_t(t = nil)
TypeFactory.iterable(t)
end
def types
Types
end
context 'when inferring ruby' do
it 'fixnum translates to PIntegerType' do
expect(calculator.infer(1).class).to eq(PIntegerType)
end
it 'large fixnum (or bignum depending on architecture) translates to PIntegerType' do
expect(calculator.infer(2**33).class).to eq(PIntegerType)
end
it 'float translates to PFloatType' do
expect(calculator.infer(1.3).class).to eq(PFloatType)
end
it 'string translates to PStringType' do
expect(calculator.infer('foo').class).to eq(PStringType)
end
it 'inferred string type knows the string value' do
t = calculator.infer('foo')
expect(t.class).to eq(PStringType)
expect(t.value).to eq('foo')
end
it 'boolean true translates to PBooleanType::TRUE' do
expect(calculator.infer(true)).to eq(PBooleanType::TRUE)
end
it 'boolean false translates to PBooleanType::FALSE' do
expect(calculator.infer(false)).to eq(PBooleanType::FALSE)
end
it 'regexp translates to PRegexpType' do
expect(calculator.infer(/^a regular expression$/).class).to eq(PRegexpType)
end
it 'iterable translates to PIteratorType' do
expect(calculator.infer(Iterable.on(1))).to be_a(PIteratorType)
end
it 'nil translates to PUndefType' do
expect(calculator.infer(nil).class).to eq(PUndefType)
end
it ':undef translates to PUndefType' do
expect(calculator.infer(:undef).class).to eq(PUndefType)
end
it 'an instance of class Foo translates to PRuntimeType[ruby, Foo]' do
::Foo = Class.new
begin
t = calculator.infer(::Foo.new)
expect(t.class).to eq(PRuntimeType)
expect(t.runtime).to eq(:ruby)
expect(t.runtime_type_name).to eq('Foo')
ensure
Object.send(:remove_const, :Foo)
end
end
it 'Class Foo translates to PTypeType[PRuntimeType[ruby, Foo]]' do
::Foo = Class.new
begin
t = calculator.infer(::Foo)
expect(t.class).to eq(PTypeType)
tt = t.type
expect(tt.class).to eq(PRuntimeType)
expect(tt.runtime).to eq(:ruby)
expect(tt.runtime_type_name).to eq('Foo')
ensure
Object.send(:remove_const, :Foo)
end
end
it 'Module FooModule translates to PTypeType[PRuntimeType[ruby, FooModule]]' do
::FooModule = Module.new
begin
t = calculator.infer(::FooModule)
expect(t.class).to eq(PTypeType)
tt = t.type
expect(tt.class).to eq(PRuntimeType)
expect(tt.runtime).to eq(:ruby)
expect(tt.runtime_type_name).to eq('FooModule')
ensure
Object.send(:remove_const, :FooModule)
end
end
context 'sensitive' do
it 'translates to PSensitiveType' do
expect(calculator.infer(PSensitiveType::Sensitive.new("hunter2")).class).to eq(PSensitiveType)
end
end
context 'binary' do
it 'translates to PBinaryType' do
expect(calculator.infer(PBinaryType::Binary.from_binary_string("binary")).class).to eq(PBinaryType)
end
end
context 'version' do
it 'translates to PVersionType' do
expect(calculator.infer(SemanticPuppet::Version.new(1,0,0)).class).to eq(PSemVerType)
end
it 'range translates to PVersionRangeType' do
expect(calculator.infer(SemanticPuppet::VersionRange.parse('1.x')).class).to eq(PSemVerRangeType)
end
it 'translates to a limited PVersionType by infer_set' do
v = SemanticPuppet::Version.new(1,0,0)
t = calculator.infer_set(v)
expect(t.class).to eq(PSemVerType)
expect(t.ranges.size).to eq(1)
expect(t.ranges[0].begin).to eq(v)
expect(t.ranges[0].end).to eq(v)
end
end
context 'timespan' do
it 'translates to PTimespanType' do
expect(calculator.infer(Time::Timespan.from_fields_hash('days' => 2))).to be_a(PTimespanType)
end
it 'translates to a limited PTimespanType by infer_set' do
ts = Time::Timespan.from_fields_hash('days' => 2)
t = calculator.infer_set(ts)
expect(t.class).to eq(PTimespanType)
expect(t.from).to be(ts)
expect(t.to).to be(ts)
end
end
context 'timestamp' do
it 'translates to PTimespanType' do
expect(calculator.infer(Time::Timestamp.now)).to be_a(PTimestampType)
end
it 'translates to a limited PTimespanType by infer_set' do
ts = Time::Timestamp.now
t = calculator.infer_set(ts)
expect(t.class).to eq(PTimestampType)
expect(t.from).to be(ts)
expect(t.to).to be(ts)
end
end
context 'array' do
let(:derived) do
Class.new(Array).new([1,2])
end
let(:derived_object) do
Class.new(Array) do
include PuppetObject
def self._pcore_type
@type ||= TypeFactory.object('name' => 'DerivedObjectArray')
end
end.new([1,2])
end
it 'translates to PArrayType' do
expect(calculator.infer([1,2]).class).to eq(PArrayType)
end
it 'translates derived Array to PRuntimeType' do
expect(calculator.infer(derived).class).to eq(PRuntimeType)
end
it 'translates derived Puppet Object Array to PObjectType' do
expect(calculator.infer(derived_object).class).to eq(PObjectType)
end
it 'Instance of derived Array class is not instance of Array type' do
expect(PArrayType::DEFAULT).not_to be_instance(derived)
end
it 'Instance of derived Array class is instance of Runtime type' do
expect(runtime_t('ruby', nil)).to be_instance(derived)
end
it 'Instance of derived Puppet Object Array class is not instance of Array type' do
expect(PArrayType::DEFAULT).not_to be_instance(derived_object)
end
it 'Instance of derived Puppet Object Array class is instance of Object type' do
expect(object_t('name' => 'DerivedObjectArray')).to be_instance(derived_object)
end
it 'with fixnum values translates to PArrayType[PIntegerType]' do
expect(calculator.infer([1,2]).element_type.class).to eq(PIntegerType)
end
it 'with 32 and 64 bit integer values translates to PArrayType[PIntegerType]' do
expect(calculator.infer([1,2**33]).element_type.class).to eq(PIntegerType)
end
it 'Range of integer values are computed' do
t = calculator.infer([-3,0,42]).element_type
expect(t.class).to eq(PIntegerType)
expect(t.from).to eq(-3)
expect(t.to).to eq(42)
end
it 'Compound string values are converted to enums' do
t = calculator.infer(['a','b', 'c']).element_type
expect(t.class).to eq(PEnumType)
expect(t.values).to eq(['a', 'b', 'c'])
end
it 'with integer and float values translates to PArrayType[PNumericType]' do
expect(calculator.infer([1,2.0]).element_type.class).to eq(PNumericType)
end
it 'with integer and string values translates to PArrayType[PScalarDataType]' do
expect(calculator.infer([1,'two']).element_type.class).to eq(PScalarDataType)
end
it 'with float and string values translates to PArrayType[PScalarDataType]' do
expect(calculator.infer([1.0,'two']).element_type.class).to eq(PScalarDataType)
end
it 'with integer, float, and string values translates to PArrayType[PScalarDataType]' do
expect(calculator.infer([1, 2.0,'two']).element_type.class).to eq(PScalarDataType)
end
it 'with integer and regexp values translates to PArrayType[PScalarType]' do
expect(calculator.infer([1, /two/]).element_type.class).to eq(PScalarType)
end
it 'with string and regexp values translates to PArrayType[PScalarType]' do
expect(calculator.infer(['one', /two/]).element_type.class).to eq(PScalarType)
end
it 'with string and symbol values translates to PArrayType[PAnyType]' do
expect(calculator.infer(['one', :two]).element_type.class).to eq(PAnyType)
end
it 'with integer and nil values translates to PArrayType[PIntegerType]' do
expect(calculator.infer([1, nil]).element_type.class).to eq(PIntegerType)
end
it 'with integer value, and array of string values, translates to Array[Data]' do
expect(calculator.infer([1, ['two']]).element_type.name).to eq('Data')
end
it 'with integer value, and hash of string => string values, translates to Array[Data]' do
expect(calculator.infer([1, {'two' => 'three'} ]).element_type.name).to eq('Data')
end
it 'with integer value, and hash of integer => string values, translates to Array[RichData]' do
expect(calculator.infer([1, {2 => 'three'} ]).element_type.name).to eq('RichData')
end
it 'with integer, regexp, and binary values translates to Array[RichData]' do
expect(calculator.infer([1, /two/, PBinaryType::Binary.from_string('three')]).element_type.name).to eq('RichData')
end
it 'with arrays of string values translates to PArrayType[PArrayType[PStringType]]' do
et = calculator.infer([['first', 'array'], ['second','array']])
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PEnumType)
end
it 'with array of string values and array of fixnums translates to PArrayType[PArrayType[PScalarDataType]]' do
et = calculator.infer([['first', 'array'], [1,2]])
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PScalarDataType)
end
it 'with hashes of string values translates to PArrayType[PHashType[PEnumType]]' do
et = calculator.infer([{:first => 'first', :second => 'second' }, {:first => 'first', :second => 'second' }])
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PHashType)
et = et.value_type
expect(et.class).to eq(PEnumType)
end
it 'with hash of string values and hash of fixnums translates to PArrayType[PHashType[PScalarDataType]]' do
et = calculator.infer([{:first => 'first', :second => 'second' }, {:first => 1, :second => 2 }])
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PHashType)
et = et.value_type
expect(et.class).to eq(PScalarDataType)
end
end
context 'hash' do
let(:derived) do
Class.new(Hash)[:first => 1, :second => 2]
end
let(:derived_object) do
Class.new(Hash) do
include PuppetObject
def self._pcore_type
@type ||= TypeFactory.object('name' => 'DerivedObjectHash')
end
end[:first => 1, :second => 2]
end
it 'translates to PHashType' do
expect(calculator.infer({:first => 1, :second => 2}).class).to eq(PHashType)
end
it 'translates derived Hash to PRuntimeType' do
expect(calculator.infer(derived).class).to eq(PRuntimeType)
end
it 'translates derived Puppet Object Hash to PObjectType' do
expect(calculator.infer(derived_object).class).to eq(PObjectType)
end
it 'Instance of derived Hash class is not instance of Hash type' do
expect(PHashType::DEFAULT).not_to be_instance(derived)
end
it 'Instance of derived Hash class is instance of Runtime type' do
expect(runtime_t('ruby', nil)).to be_instance(derived)
end
it 'Instance of derived Puppet Object Hash class is not instance of Hash type' do
expect(PHashType::DEFAULT).not_to be_instance(derived_object)
end
it 'Instance of derived Puppet Object Hash class is instance of Object type' do
expect(object_t('name' => 'DerivedObjectHash')).to be_instance(derived_object)
end
it 'with symbolic keys translates to PHashType[PRuntimeType[ruby, Symbol], value]' do
k = calculator.infer({:first => 1, :second => 2}).key_type
expect(k.class).to eq(PRuntimeType)
expect(k.runtime).to eq(:ruby)
expect(k.runtime_type_name).to eq('Symbol')
end
it 'with string keys translates to PHashType[PEnumType, value]' do
expect(calculator.infer({'first' => 1, 'second' => 2}).key_type.class).to eq(PEnumType)
end
it 'with fixnum values translates to PHashType[key, PIntegerType]' do
expect(calculator.infer({:first => 1, :second => 2}).value_type.class).to eq(PIntegerType)
end
it 'when empty infers a type that answers true to is_the_empty_hash?' do
expect(calculator.infer({}).is_the_empty_hash?).to eq(true)
expect(calculator.infer_set({}).is_the_empty_hash?).to eq(true)
end
it 'when empty is assignable to any PHashType' do
expect(calculator.assignable?(hash_t(string_t, string_t), calculator.infer({}))).to eq(true)
end
it 'when empty is not assignable to a PHashType with from size > 0' do
expect(calculator.assignable?(hash_t(string_t,string_t,range_t(1, 1)), calculator.infer({}))).to eq(false)
end
context 'using infer_set' do
it "with 'first' and 'second' keys translates to PStructType[{first=>value,second=>value}]" do
t = calculator.infer_set({'first' => 1, 'second' => 2})
expect(t.class).to eq(PStructType)
expect(t.elements.size).to eq(2)
expect(t.elements.map { |e| e.name }.sort).to eq(['first', 'second'])
end
it 'with string keys and string and array values translates to PStructType[{key1=>PStringType,key2=>PTupleType}]' do
t = calculator.infer_set({ 'mode' => 'read', 'path' => ['foo', 'fee' ] })
expect(t.class).to eq(PStructType)
expect(t.elements.size).to eq(2)
els = t.elements.map { |e| e.value_type }.sort {|a,b| a.to_s <=> b.to_s }
expect(els[0].class).to eq(PStringType)
expect(els[1].class).to eq(PTupleType)
end
it 'with mixed string and non-string keys translates to PHashType' do
t = calculator.infer_set({ 1 => 'first', 'second' => 'second' })
expect(t.class).to eq(PHashType)
end
it 'with empty string keys translates to PHashType' do
t = calculator.infer_set({ '' => 'first', 'second' => 'second' })
expect(t.class).to eq(PHashType)
end
end
end
it 'infers an instance of an anonymous class to Runtime[ruby]' do
cls = Class.new do
attr_reader :name
def initialize(name)
@name = name
end
end
t = calculator.infer(cls.new('test'))
expect(t.class).to eql(PRuntimeType)
expect(t.runtime).to eql(:ruby)
expect(t.name_or_pattern).to eql(nil)
end
end
context 'patterns' do
it 'constructs a PPatternType' do
t = pattern_t('a(b)c')
expect(t.class).to eq(PPatternType)
expect(t.patterns.size).to eq(1)
expect(t.patterns[0].class).to eq(PRegexpType)
expect(t.patterns[0].pattern).to eq('a(b)c')
expect(t.patterns[0].regexp.match('abc')[1]).to eq('b')
end
it 'constructs a PEnumType with multiple strings' do
t = enum_t('a', 'b', 'c', 'abc')
expect(t.values).to eq(['a', 'b', 'c', 'abc'].sort)
end
end
# Deal with cases not covered by computing common type
context 'when computing common type' do
it 'computes given resource type commonality' do
r1 = PResourceType.new('File', nil)
r2 = PResourceType.new('File', nil)
expect(calculator.common_type(r1, r2).to_s).to eq('File')
r2 = PResourceType.new('File', '/tmp/foo')
expect(calculator.common_type(r1, r2).to_s).to eq('File')
r1 = PResourceType.new('File', '/tmp/foo')
expect(calculator.common_type(r1, r2).to_s).to eq("File['/tmp/foo']")
r1 = PResourceType.new('File', '/tmp/bar')
expect(calculator.common_type(r1, r2).to_s).to eq('File')
r2 = PResourceType.new('Package', 'apache')
expect(calculator.common_type(r1, r2).to_s).to eq('Resource')
end
it 'computes given hostclass type commonality' do
r1 = PClassType.new('foo')
r2 = PClassType.new('foo')
expect(calculator.common_type(r1, r2).to_s).to eq('Class[foo]')
r2 = PClassType.new('bar')
expect(calculator.common_type(r1, r2).to_s).to eq('Class')
r2 = PClassType.new(nil)
expect(calculator.common_type(r1, r2).to_s).to eq('Class')
r1 = PClassType.new(nil)
expect(calculator.common_type(r1, r2).to_s).to eq('Class')
end
context 'of strings' do
it 'computes commonality' do
t1 = string_t('abc')
t2 = string_t('xyz')
common_t = calculator.common_type(t1,t2)
expect(common_t.class).to eq(PEnumType)
expect(common_t.values).to eq(['abc', 'xyz'])
end
it 'computes common size_type' do
t1 = constrained_string_t(range_t(3,6))
t2 = constrained_string_t(range_t(2,4))
common_t = calculator.common_type(t1,t2)
expect(common_t.class).to eq(PStringType)
expect(common_t.size_type).to eq(range_t(2,6))
end
it 'computes common size_type to be undef when one of the types has no size_type' do
t1 = string_t
t2 = constrained_string_t(range_t(2,4))
common_t = calculator.common_type(t1,t2)
expect(common_t.class).to eq(PStringType)
expect(common_t.size_type).to be_nil
end
it 'computes values to be empty if the one has empty values' do
t1 = string_t('apa')
t2 = constrained_string_t(range_t(2,4))
common_t = calculator.common_type(t1,t2)
expect(common_t.class).to eq(PStringType)
expect(common_t.value).to be_nil
end
end
it 'computes pattern commonality' do
t1 = pattern_t('abc')
t2 = pattern_t('xyz')
common_t = calculator.common_type(t1,t2)
expect(common_t.class).to eq(PPatternType)
expect(common_t.patterns.map { |pr| pr.pattern }).to eq(['abc', 'xyz'])
expect(common_t.to_s).to eq('Pattern[/abc/, /xyz/]')
end
it 'computes enum commonality to value set sum' do
t1 = enum_t('a', 'b', 'c')
t2 = enum_t('x', 'y', 'z')
common_t = calculator.common_type(t1, t2)
expect(common_t).to eq(enum_t('a', 'b', 'c', 'x', 'y', 'z'))
end
it 'computed variant commonality to type union where added types are not sub-types' do
a_t1 = integer_t
a_t2 = enum_t('b')
v_a = variant_t(a_t1, a_t2)
b_t1 = integer_t
b_t2 = enum_t('a')
v_b = variant_t(b_t1, b_t2)
common_t = calculator.common_type(v_a, v_b)
expect(common_t.class).to eq(PVariantType)
expect(Set.new(common_t.types)).to eq(Set.new([a_t1, a_t2, b_t1, b_t2]))
end
it 'computed variant commonality to type union where added types are sub-types' do
a_t1 = integer_t
a_t2 = string_t
v_a = variant_t(a_t1, a_t2)
b_t1 = integer_t
b_t2 = enum_t('a')
v_b = variant_t(b_t1, b_t2)
common_t = calculator.common_type(v_a, v_b)
expect(common_t.class).to eq(PVariantType)
expect(Set.new(common_t.types)).to eq(Set.new([a_t1, a_t2]))
end
context 'commonality of scalar data types' do
it 'Numeric and String == ScalarData' do
expect(calculator.common_type(PNumericType::DEFAULT, PStringType::DEFAULT).class).to eq(PScalarDataType)
end
it 'Numeric and Boolean == ScalarData' do
expect(calculator.common_type(PNumericType::DEFAULT, PBooleanType::DEFAULT).class).to eq(PScalarDataType)
end
it 'String and Boolean == ScalarData' do
expect(calculator.common_type(PStringType::DEFAULT, PBooleanType::DEFAULT).class).to eq(PScalarDataType)
end
end
context 'commonality of scalar types' do
it 'Regexp and Integer == Scalar' do
expect(calculator.common_type(PRegexpType::DEFAULT, PScalarDataType::DEFAULT).class).to eq(PScalarType)
end
it 'Regexp and SemVer == ScalarData' do
expect(calculator.common_type(PRegexpType::DEFAULT, PSemVerType::DEFAULT).class).to eq(PScalarType)
end
it 'Timestamp and Timespan == ScalarData' do
expect(calculator.common_type(PTimestampType::DEFAULT, PTimespanType::DEFAULT).class).to eq(PScalarType)
end
it 'Timestamp and Boolean == ScalarData' do
expect(calculator.common_type(PTimestampType::DEFAULT, PBooleanType::DEFAULT).class).to eq(PScalarType)
end
end
context 'of callables' do
it 'incompatible instances => generic callable' do
t1 = callable_t(String)
t2 = callable_t(Integer)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(PCallableType)
expect(common_t.param_types).to be_nil
expect(common_t.block_type).to be_nil
end
it 'compatible instances => the most specific' do
t1 = callable_t(String)
scalar_t = PScalarType.new
t2 = callable_t(scalar_t)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(PCallableType)
expect(common_t.param_types.class).to be(PTupleType)
expect(common_t.param_types.types).to eql([string_t])
expect(common_t.block_type).to be_nil
end
it 'block_type is included in the check (incompatible block)' do
b1 = callable_t(String)
b2 = callable_t(Integer)
t1 = callable_t(String, b1)
t2 = callable_t(String, b2)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(PCallableType)
expect(common_t.param_types).to be_nil
expect(common_t.block_type).to be_nil
end
it 'block_type is included in the check (compatible block)' do
b1 = callable_t(String)
t1 = callable_t(String, b1)
scalar_t = PScalarType::DEFAULT
b2 = callable_t(scalar_t)
t2 = callable_t(String, b2)
common_t = calculator.common_type(t1, t2)
expect(common_t.param_types.class).to be(PTupleType)
expect(common_t.block_type).to eql(callable_t(scalar_t))
end
it 'return_type is included in the check (incompatible return_type)' do
t1 = callable_t([String], String)
t2 = callable_t([String], Integer)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(PCallableType)
expect(common_t.param_types).to be_nil
expect(common_t.return_type).to be_nil
end
it 'return_type is included in the check (compatible return_type)' do
t1 = callable_t([String], Numeric)
t2 = callable_t([String], Integer)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(PCallableType)
expect(common_t.param_types).to be_a(PTupleType)
expect(common_t.return_type).to eql(PNumericType::DEFAULT)
end
end
end
context 'computes assignability' do
include_context 'types_setup'
it 'such that all types are assignable to themselves' do
all_types.each do |tc|
t = tc::DEFAULT
expect(t).to be_assignable_to(t)
end
end
context 'for Unit, such that' do
it 'all types are assignable to Unit' do
t = PUnitType::DEFAULT
all_types.each { |t2| expect(t2::DEFAULT).to be_assignable_to(t) }
end
it 'Unit is assignable to all other types' do
t = PUnitType::DEFAULT
all_types.each { |t2| expect(t).to be_assignable_to(t2::DEFAULT) }
end
it 'Unit is assignable to Unit' do
t = PUnitType::DEFAULT
t2 = PUnitType::DEFAULT
expect(t).to be_assignable_to(t2)
end
end
context 'for Any, such that' do
it 'all types are assignable to Any' do
t = PAnyType::DEFAULT
all_types.each { |t2| expect(t2::DEFAULT).to be_assignable_to(t) }
end
it 'Any is not assignable to anything but Any and Optional (implied Optional[Any])' do
tested_types = all_types() - [PAnyType, POptionalType]
t = PAnyType::DEFAULT
tested_types.each { |t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
end
context "for NotUndef, such that" do
it 'all types except types assignable from Undef are assignable to NotUndef' do
t = not_undef_t
tc = TypeCalculator.singleton
undef_t = PUndefType::DEFAULT
all_types.each do |c|
t2 = c::DEFAULT
if tc.assignable?(t2, undef_t)
expect(t2).not_to be_assignable_to(t)
else
expect(t2).to be_assignable_to(t)
end
end
end
it 'type NotUndef[T] is assignable from T unless T is assignable from Undef ' do
tc = TypeCalculator.singleton
undef_t = PUndefType::DEFAULT
all_types().select do |c|
t2 = c::DEFAULT
not_undef_t = not_undef_t(t2)
if tc.assignable?(t2, undef_t)
expect(t2).not_to be_assignable_to(not_undef_t)
else
expect(t2).to be_assignable_to(not_undef_t)
end
end
end
it 'type T is assignable from NotUndef[T] unless T is assignable from Undef' do
tc = TypeCalculator.singleton
undef_t = PUndefType::DEFAULT
all_types().select do |c|
t2 = c::DEFAULT
not_undef_t = not_undef_t(t2)
unless tc.assignable?(t2, undef_t)
expect(not_undef_t).to be_assignable_to(t2)
end
end
end
end
context "for TypeReference, such that" do
it 'no other type is assignable' do
t = PTypeReferenceType::DEFAULT
all_instances = (all_types - [
PTypeReferenceType, # Avoid comparison with t
PTypeAliasType # DEFAULT resolves to PTypeReferenceType::DEFAULT, i.e. t
]).map {|c| c::DEFAULT }
# Add a non-empty variant
all_instances << variant_t(PAnyType::DEFAULT, PUnitType::DEFAULT)
# Add a type alias that doesn't resolve to 't'
all_instances << type_alias_t('MyInt', 'Integer').resolve(nil)
all_instances.each { |i| expect(i).not_to be_assignable_to(t) }
end
it 'a TypeReference to the exact same type is assignable' do
expect(type_reference_t('Integer[0,10]')).to be_assignable_to(type_reference_t('Integer[0,10]'))
end
it 'a TypeReference to the different type is not assignable' do
expect(type_reference_t('String')).not_to be_assignable_to(type_reference_t('Integer'))
end
it 'a TypeReference to the different type is not assignable even if the referenced type is' do
expect(type_reference_t('Integer[1,2]')).not_to be_assignable_to(type_reference_t('Integer[0,3]'))
end
end
context 'for Data, such that' do
let(:data) { TypeFactory.data }
data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc|
it "it is assignable from #{tc.name}" do
expect(tc).to be_assignable_to(data)
end
end
data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc|
it "it is assignable from Optional[#{tc.name}]" do
expect(optional_t(tc)).to be_assignable_to(data)
end
end
it 'it is not assignable to any of its subtypes' do
types_to_test = data_compatible_types
types_to_test.each {|t2| expect(data).not_to be_assignable_to(type_from_class(t2)) }
end
it 'it is not assignable to any disjunct type' do
tested_types = all_types - [PAnyType, POptionalType, PInitType] - scalar_data_types
tested_types.each {|t2| expect(data).not_to be_assignable_to(t2::DEFAULT) }
end
end
context 'for Rich Data, such that' do
let(:rich_data) { TypeFactory.rich_data }
rich_data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc|
it "it is assignable from #{tc.name}" do
expect(tc).to be_assignable_to(rich_data)
end
end
rich_data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc|
it "it is assignable from Optional[#{tc.name}]" do
expect(optional_t(tc)).to be_assignable_to(rich_data)
end
end
it 'it is not assignable to any of its subtypes' do
types_to_test = rich_data_compatible_types
types_to_test.each {|t2| expect(rich_data).not_to be_assignable_to(type_from_class(t2)) }
end
it 'it is not assignable to any disjunct type' do
tested_types = all_types - [PAnyType, POptionalType, PInitType] - scalar_types
tested_types.each {|t2| expect(rich_data).not_to be_assignable_to(t2::DEFAULT) }
end
end
context 'for Variant, such that' do
it 'it is assignable to a type if all contained types are assignable to that type' do
v = variant_t(range_t(10, 12),range_t(14, 20))
expect(v).to be_assignable_to(integer_t)
expect(v).to be_assignable_to(range_t(10, 20))
# test that both types are assignable to one of the variants OK
expect(v).to be_assignable_to(variant_t(range_t(10, 20), range_t(30, 40)))
# test where each type is assignable to different types in a variant is OK
expect(v).to be_assignable_to(variant_t(range_t(10, 13), range_t(14, 40)))
# not acceptable
expect(v).not_to be_assignable_to(range_t(0, 4))
expect(v).not_to be_assignable_to(string_t)
end
it 'an empty Variant is assignable to another empty Variant' do
expect(empty_variant_t).to be_assignable_to(empty_variant_t)
end
it 'an empty Variant is assignable to Any' do
expect(empty_variant_t).to be_assignable_to(PAnyType::DEFAULT)
end
it 'an empty Variant is assignable to Unit' do
expect(empty_variant_t).to be_assignable_to(PUnitType::DEFAULT)
end
it 'an empty Variant is not assignable to any type except empty Variant, Any, NotUndef, and Unit' do
assignables = [PUnitType, PAnyType, PNotUndefType]
unassignables = all_types - assignables
unassignables.each {|t2| expect(empty_variant_t).not_to be_assignable_to(t2::DEFAULT) }
assignables.each {|t2| expect(empty_variant_t).to be_assignable_to(t2::DEFAULT) }
end
it 'an empty Variant is not assignable to Optional[Any] since it is not assignable to Undef' do
opt_any = optional_t(any_t)
expect(empty_variant_t).not_to be_assignable_to(opt_any)
end
it 'an Optional[Any] is not assignable to empty Variant' do
opt_any = optional_t(any_t)
expect(opt_any).not_to be_assignable_to(empty_variant_t)
end
it 'an empty Variant is assignable to NotUndef[Variant] since Variant is not Undef' do
not_undef_variant = not_undef_t(empty_variant_t)
expect(empty_variant_t).to be_assignable_to(not_undef_variant)
end
it 'a NotUndef[Variant] is assignable to empty Variant' do
not_undef_variant = not_undef_t(empty_variant_t)
expect(not_undef_variant).to be_assignable_to(empty_variant_t)
end
end
context 'for Scalar, such that' do
it 'all scalars are assignable to Scalar' do
t = PScalarType::DEFAULT
scalar_types.each {|t2| expect(t2::DEFAULT).to be_assignable_to(t) }
end
it 'Scalar is not assignable to any of its subtypes' do
t = PScalarType::DEFAULT
types_to_test = scalar_types - [PScalarType]
types_to_test.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
it 'Scalar is not assignable to any disjunct type' do
tested_types = all_types - [PAnyType, POptionalType, PInitType, PNotUndefType] - scalar_types
t = PScalarType::DEFAULT
tested_types.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
end
context 'for Numeric, such that' do
it 'all numerics are assignable to Numeric' do
t = PNumericType::DEFAULT
numeric_types.each {|t2| expect(t2::DEFAULT).to be_assignable_to(t) }
end
it 'Numeric is not assignable to any of its subtypes' do
t = PNumericType::DEFAULT
types_to_test = numeric_types - [PNumericType]
types_to_test.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
it 'Numeric does not consider ruby Rational to be an instance' do
t = PNumericType::DEFAULT
expect(t).not_to be_instance(Rational(2,3))
end
it 'Numeric is not assignable to any disjunct type' do
tested_types = all_types - [
PAnyType,
POptionalType,
PInitType,
PNotUndefType,
PScalarType,
PScalarDataType,
] - numeric_types
t = PNumericType::DEFAULT
tested_types.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
end
context 'for Collection, such that' do
it 'all collections are assignable to Collection' do
t = PCollectionType::DEFAULT
collection_types.each {|t2| expect(t2::DEFAULT).to be_assignable_to(t) }
end
it 'Collection is not assignable to any of its subtypes' do
t = PCollectionType::DEFAULT
types_to_test = collection_types - [PCollectionType]
types_to_test.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
it 'Collection is not assignable to any disjunct type' do
tested_types = all_types - [
PAnyType,
POptionalType,
PNotUndefType,
PIterableType] - collection_types
t = PCollectionType::DEFAULT
tested_types.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
end
context 'for Array, such that' do
it 'Array is not assignable to non Array based Collection type' do
t = PArrayType::DEFAULT
tested_types = collection_types - [
PCollectionType,
PNotUndefType,
PArrayType,
PTupleType]
tested_types.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
it 'Array is not assignable to any disjunct type' do
tested_types = all_types - [
PAnyType,
POptionalType,
PNotUndefType,
PIterableType] - collection_types
t = PArrayType::DEFAULT
tested_types.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
it 'Empty Array is assignable to an array that accepts 0 entries' do
expect(empty_array_t).to be_assignable_to(array_t(string_t))
expect(empty_array_t).to be_assignable_to(array_t(integer_t))
end
it 'A Tuple is assignable to an array' do
expect(tuple_t(String)).to be_assignable_to(array_t(String))
end
it 'A Tuple with <n> elements is assignable to an array with min size <n>' do
expect(tuple_t(String,String)).to be_assignable_to(array_t(String, range_t(2, :default)))
end
it 'A Tuple with <n> elements where the last 2 are optional is assignable to an array with size <n> - 2' do
expect(constrained_tuple_t(range_t(2, :default), String,String,String,String)).to be_assignable_to(array_t(String, range_t(2, :default)))
end
end
context 'for Enum, such that' do
it 'Enum is assignable to an Enum with all contained options' do
expect(enum_t('a', 'b')).to be_assignable_to(enum_t('a', 'b', 'c'))
end
it 'Enum is not assignable to an Enum with fewer contained options' do
expect(enum_t('a', 'b')).not_to be_assignable_to(enum_t('a'))
end
it 'case insensitive Enum is not assignable to case sensitive Enum' do
expect(enum_t('a', 'b', true)).not_to be_assignable_to(enum_t('a', 'b'))
end
it 'case sensitive Enum is assignable to case insensitive Enum' do
expect(enum_t('a', 'b')).to be_assignable_to(enum_t('a', 'b', true))
end
it 'case sensitive Enum is not assignable to case sensitive Enum using different case' do
expect(enum_t('a', 'b')).not_to be_assignable_to(enum_t('A', 'B'))
end
it 'case sensitive Enum is assignable to case insensitive Enum using different case' do
expect(enum_t('a', 'b')).to be_assignable_to(enum_t('A', 'B', true))
end
end
context 'for Hash, such that' do
it 'Hash is not assignable to any other Collection type' do
t = PHashType::DEFAULT
tested_types = collection_types - [
PCollectionType,
PStructType,
PHashType]
tested_types.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
it 'Hash is not assignable to any disjunct type' do
tested_types = all_types - [
PAnyType,
POptionalType,
PNotUndefType,
PIterableType] - collection_types
t = PHashType::DEFAULT
tested_types.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
it 'Struct is assignable to Hash with Pattern that matches all keys' do
expect(struct_t({'x' => integer_t, 'y' => integer_t})).to be_assignable_to(hash_t(pattern_t(/^\w+$/), factory.any))
end
it 'Struct is assignable to Hash with Enum that matches all keys' do
expect(struct_t({'x' => integer_t, 'y' => integer_t})).to be_assignable_to(hash_t(enum_t('x', 'y', 'z'), factory.any))
end
it 'Struct is not assignable to Hash with Pattern unless all keys match' do
expect(struct_t({'a' => integer_t, 'A' => integer_t})).not_to be_assignable_to(hash_t(pattern_t(/^[A-Z]+$/), factory.any))
end
it 'Struct is not assignable to Hash with Enum unless all keys match' do
expect(struct_t({'a' => integer_t, 'y' => integer_t})).not_to be_assignable_to(hash_t(enum_t('x', 'y', 'z'), factory.any))
end
end
context 'for Timespan such that' do
it 'Timespan is assignable to less constrained Timespan' do
t1 = PTimespanType.new('00:00:10', '00:00:20')
t2 = PTimespanType.new('00:00:11', '00:00:19')
expect(t2).to be_assignable_to(t1)
end
it 'Timespan is not assignable to more constrained Timespan' do
t1 = PTimespanType.new('00:00:10', '00:00:20')
t2 = PTimespanType.new('00:00:11', '00:00:19')
expect(t1).not_to be_assignable_to(t2)
end
end
context 'for Timestamp such that' do
it 'Timestamp is assignable to less constrained Timestamp' do
t1 = PTimestampType.new('2016-01-01', '2016-12-31')
t2 = PTimestampType.new('2016-02-01', '2016-11-30')
expect(t2).to be_assignable_to(t1)
end
it 'Timestamp is not assignable to more constrained Timestamp' do
t1 = PTimestampType.new('2016-01-01', '2016-12-31')
t2 = PTimestampType.new('2016-02-01', '2016-11-30')
expect(t1).not_to be_assignable_to(t2)
end
end
context 'for Tuple, such that' do
it 'Tuple is not assignable to any other non Array based Collection type' do
t = PTupleType::DEFAULT
tested_types = collection_types - [
PCollectionType,
PTupleType,
PArrayType]
tested_types.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
it 'A tuple with parameters is assignable to the default Tuple' do
t = PTupleType::DEFAULT
t2 = PTupleType.new([PStringType::DEFAULT])
expect(t2).to be_assignable_to(t)
end
it 'Tuple is not assignable to any disjunct type' do
tested_types = all_types - [
PAnyType,
POptionalType,
PInitType,
PNotUndefType,
PIterableType] - collection_types
t = PTupleType::DEFAULT
tested_types.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
end
context 'for Struct, such that' do
it 'Struct is not assignable to any other non Hashed based Collection type' do
t = PStructType::DEFAULT
tested_types = collection_types - [
PCollectionType,
PStructType,
PHashType,
PInitType]
tested_types.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
it 'Struct is not assignable to any disjunct type' do
tested_types = all_types - [
PAnyType,
POptionalType,
PNotUndefType,
PIterableType,
PInitType] - collection_types
t = PStructType::DEFAULT
tested_types.each {|t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
it 'Default key optionality is controlled by value assignability to undef' do
t1 = struct_t({'member' => string_t})
expect(t1.elements[0].key_type).to eq(string_t('member'))
t1 = struct_t({'member' => any_t})
expect(t1.elements[0].key_type).to eq(optional_t(string_t('member')))
end
it "NotUndef['key'] becomes String['key'] (since its implied that String is required)" do
t1 = struct_t({not_undef_t('member') => string_t})
expect(t1.elements[0].key_type).to eq(string_t('member'))
end
it "Optional['key'] becomes Optional[String['key']]" do
t1 = struct_t({optional_t('member') => string_t})
expect(t1.elements[0].key_type).to eq(optional_t(string_t('member')))
end
it 'Optional members are not required' do
t1 = struct_t({optional_t('optional_member') => string_t, not_undef_t('other_member') => string_t})
t2 = struct_t({not_undef_t('other_member') => string_t})
expect(t2).to be_assignable_to(t1)
end
it 'Required members not optional even when value is' do
t1 = struct_t({not_undef_t('required_member') => any_t, not_undef_t('other_member') => string_t})
t2 = struct_t({not_undef_t('other_member') => string_t})
expect(t2).not_to be_assignable_to(t1)
end
it 'A hash of string is not assignable to struct with integer value' do
t1 = struct_t({'foo' => integer_t, 'bar' => string_t})
t2 = hash_t(string_t, string_t, range_t(2, 2))
expect(t1.assignable?(t2)).to eql(false)
end
it 'A hash of with integer key is not assignable to struct with string key' do
t1 = struct_t({'foo' => string_t, 'bar' => string_t})
t2 = hash_t(integer_t, string_t, range_t(2, 2))
expect(t1.assignable?(t2)).to eql(false)
end
end
context 'for Callable, such that' do
it 'Callable is not assignable to any disjunct type' do
t = PCallableType::DEFAULT
tested_types = all_types - [
PCallableType,
PAnyType,
POptionalType,
PNotUndefType]
tested_types.each {|t2| expect(t).to_not be_assignable_to(t2::DEFAULT) }
end
it 'a callable with parameter is assignable to the default callable' do
expect(callable_t(string_t)).to be_assignable_to(PCallableType::DEFAULT)
end
it 'the default callable is not assignable to a callable with parameter' do
expect(PCallableType::DEFAULT).not_to be_assignable_to(callable_t(string_t))
end
it 'a callable with a return type is assignable to the default callable' do
expect(callable_t([], string_t)).to be_assignable_to(PCallableType::DEFAULT)
end
it 'the default callable is not assignable to a callable with a return type' do
expect(PCallableType::DEFAULT).not_to be_assignable_to(callable_t([],string_t))
end
it 'a callable with a return type Any is assignable to the default callable' do
expect(callable_t([], any_t)).to be_assignable_to(PCallableType::DEFAULT)
end
it 'a callable with a return type Any is equal to a callable with the same parameters and no return type' do
expect(callable_t([string_t], any_t)).to eql(callable_t(string_t))
end
it 'a callable with a return type different than Any is not equal to a callable with the same parameters and no return type' do
expect(callable_t([string_t], string_t)).not_to eql(callable_t(string_t))
end
it 'a callable with a return type is assignable from another callable with an assignable return type' do
expect(callable_t([], string_t)).to be_assignable_to(callable_t([], PScalarType::DEFAULT))
end
it 'a callable with a return type is not assignable from another callable unless the return type is assignable' do
expect(callable_t([], string_t)).not_to be_assignable_to(callable_t([], integer_t))
end
end
it 'should recognize mapped ruby types' do
{ Integer => PIntegerType::DEFAULT,
Fixnum => PIntegerType::DEFAULT,
Bignum => PIntegerType::DEFAULT,
Float => PFloatType::DEFAULT,
Numeric => PNumericType::DEFAULT,
NilClass => PUndefType::DEFAULT,
TrueClass => PBooleanType::DEFAULT,
FalseClass => PBooleanType::DEFAULT,
String => PStringType::DEFAULT,
Regexp => PRegexpType::DEFAULT,
Regexp => PRegexpType::DEFAULT,
Array => TypeFactory.array_of_any,
Hash => TypeFactory.hash_of_any
}.each do |ruby_type, puppet_type |
expect(ruby_type).to be_assignable_to(puppet_type)
end
end
context 'when dealing with integer ranges' do
it 'should accept an equal range' do
expect(calculator.assignable?(range_t(2,5), range_t(2,5))).to eq(true)
end
it 'should accept a narrower range' do
expect(calculator.assignable?(range_t(2,10), range_t(3,5))).to eq(true)
end
it 'should reject a wider range' do
expect(calculator.assignable?(range_t(3,5), range_t(2,10))).to eq(false)
end
it 'should reject a partially overlapping range' do
expect(calculator.assignable?(range_t(3,5), range_t(2,4))).to eq(false)
expect(calculator.assignable?(range_t(3,5), range_t(4,6))).to eq(false)
end
end
context 'when dealing with patterns' do
it 'should accept a string matching a pattern' do
p_t = pattern_t('abc')
p_s = string_t('XabcY')
expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should accept a regexp matching a pattern' do
p_t = pattern_t(/abc/)
p_s = string_t('XabcY')
expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should accept a pattern matching a pattern' do
p_t = pattern_t(pattern_t('abc'))
p_s = string_t('XabcY')
expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should accept a regexp matching a pattern' do
p_t = pattern_t(regexp_t('abc'))
p_s = string_t('XabcY')
expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should accept a string matching all patterns' do
p_t = pattern_t('abc', 'ab', 'c')
p_s = string_t('XabcY')
expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should accept multiple strings if they all match any patterns' do
p_t = pattern_t('X', 'Y', 'abc')
p_s = enum_t('Xa', 'aY', 'abc')
expect(calculator.assignable?(p_t, p_s)).to eq(true)
end
it 'should reject a string not matching any patterns' do
p_t = pattern_t('abc', 'ab', 'c')
p_s = string_t('XqqqY')
expect(calculator.assignable?(p_t, p_s)).to eq(false)
end
it 'should reject multiple strings if not all match any patterns' do
p_t = pattern_t('abc', 'ab', 'c', 'q')
p_s = enum_t('X', 'Y', 'Z')
expect(calculator.assignable?(p_t, p_s)).to eq(false)
end
it 'should accept enum matching patterns as instanceof' do
enum = enum_t('XS', 'S', 'M', 'L' 'XL', 'XXL')
pattern = pattern_t('S', 'M', 'L')
expect(calculator.assignable?(pattern, enum)).to eq(true)
end
it 'pattern should accept a variant where all variants are acceptable' do
pattern = pattern_t(/^\w+$/)
expect(calculator.assignable?(pattern, variant_t(string_t('a'), string_t('b')))).to eq(true)
end
it 'pattern representing all patterns should accept any pattern' do
expect(calculator.assignable?(pattern_t, pattern_t('a'))).to eq(true)
expect(calculator.assignable?(pattern_t, pattern_t)).to eq(true)
end
it 'pattern representing all patterns should accept any enum' do
expect(calculator.assignable?(pattern_t, enum_t('a'))).to eq(true)
expect(calculator.assignable?(pattern_t, enum_t)).to eq(true)
end
it 'pattern representing all patterns should accept any string' do
expect(calculator.assignable?(pattern_t, string_t('a'))).to eq(true)
expect(calculator.assignable?(pattern_t, string_t)).to eq(true)
end
end
context 'when dealing with enums' do
it 'should accept a string with matching content' do
expect(calculator.assignable?(enum_t('a', 'b'), string_t('a'))).to eq(true)
expect(calculator.assignable?(enum_t('a', 'b'), string_t('b'))).to eq(true)
expect(calculator.assignable?(enum_t('a', 'b'), string_t('c'))).to eq(false)
end
it 'should accept an enum with matching enum' do
expect(calculator.assignable?(enum_t('a', 'b'), enum_t('a', 'b'))).to eq(true)
expect(calculator.assignable?(enum_t('a', 'b'), enum_t('a'))).to eq(true)
expect(calculator.assignable?(enum_t('a', 'b'), enum_t('c'))).to eq(false)
end
it 'non parameterized enum accepts any other enum but not the reverse' do
expect(calculator.assignable?(enum_t, enum_t('a'))).to eq(true)
expect(calculator.assignable?(enum_t('a'), enum_t)).to eq(false)
end
it 'enum should accept a variant where all variants are acceptable' do
enum = enum_t('a', 'b')
expect(calculator.assignable?(enum, variant_t(string_t('a'), string_t('b')))).to eq(true)
end
end
context 'when dealing with string and enum combinations' do
it 'should accept assigning any enum to unrestricted string' do
expect(calculator.assignable?(string_t, enum_t('blue'))).to eq(true)
expect(calculator.assignable?(string_t, enum_t('blue', 'red'))).to eq(true)
end
it 'should not accept assigning longer enum value to size restricted string' do
expect(calculator.assignable?(constrained_string_t(range_t(2,2)), enum_t('a','blue'))).to eq(false)
end
it 'should accept assigning any string to empty enum' do
expect(calculator.assignable?(enum_t, string_t)).to eq(true)
end
it 'should accept assigning empty enum to any string' do
expect(calculator.assignable?(string_t, enum_t)).to eq(true)
end
it 'should not accept assigning empty enum to size constrained string' do
expect(calculator.assignable?(constrained_string_t(range_t(2,2)), enum_t)).to eq(false)
end
end
context 'when dealing with string/pattern/enum combinations' do
it 'any string is equal to any enum is equal to any pattern' do
expect(calculator.assignable?(string_t, enum_t)).to eq(true)
expect(calculator.assignable?(string_t, pattern_t)).to eq(true)
expect(calculator.assignable?(enum_t, string_t)).to eq(true)
expect(calculator.assignable?(enum_t, pattern_t)).to eq(true)
expect(calculator.assignable?(pattern_t, string_t)).to eq(true)
expect(calculator.assignable?(pattern_t, enum_t)).to eq(true)
end
end
context 'when dealing with tuples' do
it 'matches empty tuples' do
tuple1 = tuple_t
tuple2 = tuple_t
expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
expect(calculator.assignable?(tuple2, tuple1)).to eq(true)
end
it 'accepts an empty tuple as assignable to a tuple with a min size of 0' do
tuple1 = constrained_tuple_t(range_t(0, :default))
tuple2 = tuple_t()
expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
expect(calculator.assignable?(tuple2, tuple1)).to eq(true)
end
it 'should accept matching tuples' do
tuple1 = tuple_t(1,2)
tuple2 = tuple_t(Integer,Integer)
expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
expect(calculator.assignable?(tuple2, tuple1)).to eq(true)
end
it 'should accept matching tuples where one is more general than the other' do
tuple1 = tuple_t(1,2)
tuple2 = tuple_t(Numeric,Numeric)
expect(calculator.assignable?(tuple1, tuple2)).to eq(false)
expect(calculator.assignable?(tuple2, tuple1)).to eq(true)
end
it 'should accept ranged tuples' do
tuple1 = constrained_tuple_t(range_t(5,5), 1)
tuple2 = tuple_t(Integer,Integer, Integer, Integer, Integer)
expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
expect(calculator.assignable?(tuple2, tuple1)).to eq(true)
end
it 'should reject ranged tuples when ranges does not match' do
tuple1 = constrained_tuple_t(range_t(4, 5), 1)
tuple2 = tuple_t(Integer,Integer, Integer, Integer, Integer)
expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
expect(calculator.assignable?(tuple2, tuple1)).to eq(false)
end
it 'should reject ranged tuples when ranges does not match (using infinite upper bound)' do
tuple1 = constrained_tuple_t(range_t(4, :default), 1)
tuple2 = tuple_t(Integer,Integer, Integer, Integer, Integer)
expect(calculator.assignable?(tuple1, tuple2)).to eq(true)
expect(calculator.assignable?(tuple2, tuple1)).to eq(false)
end
it 'should accept matching tuples with optional entries by repeating last' do
tuple1 = constrained_tuple_t(range_t(0, :default), 1,2)
tuple2 = constrained_tuple_t(range_t(0, :default), Numeric,Numeric)
expect(calculator.assignable?(tuple1, tuple2)).to eq(false)
expect(calculator.assignable?(tuple2, tuple1)).to eq(true)
end
it 'should accept matching tuples with optional entries' do
tuple1 = constrained_tuple_t(range_t(1, 3), Integer, Integer, String)
array2 = array_t(Integer, range_t(2,2))
expect(calculator.assignable?(tuple1, array2)).to eq(true)
tuple1 = constrained_tuple_t(range_t(3, 3), tuple1.types)
expect(calculator.assignable?(tuple1, array2)).to eq(false)
end
it 'should accept matching array' do
tuple1 = tuple_t(1,2)
array = array_t(Integer, range_t(2, 2))
expect(calculator.assignable?(tuple1, array)).to eq(true)
expect(calculator.assignable?(array, tuple1)).to eq(true)
end
it 'should accept empty array when tuple allows min of 0' do
tuple1 = constrained_tuple_t(range_t(0, 1), Integer)
array = array_t(unit_t, range_t(0, 0))
expect(calculator.assignable?(tuple1, array)).to eq(true)
expect(calculator.assignable?(array, tuple1)).to eq(false)
end
end
context 'when dealing with structs' do
it 'should accept matching structs' do
struct1 = struct_t({'a'=>Integer, 'b'=>Integer})
struct2 = struct_t({'a'=>Integer, 'b'=>Integer})
expect(calculator.assignable?(struct1, struct2)).to eq(true)
expect(calculator.assignable?(struct2, struct1)).to eq(true)
end
it 'should accept matching structs with less elements when unmatched elements are optional' do
struct1 = struct_t({'a'=>Integer, 'b'=>Integer, 'c'=>optional_t(Integer)})
struct2 = struct_t({'a'=>Integer, 'b'=>Integer})
expect(calculator.assignable?(struct1, struct2)).to eq(true)
end
it 'should reject matching structs with more elements even if excess elements are optional' do
struct1 = struct_t({'a'=>Integer, 'b'=>Integer})
struct2 = struct_t({'a'=>Integer, 'b'=>Integer, 'c'=>optional_t(Integer)})
expect(calculator.assignable?(struct1, struct2)).to eq(false)
end
it 'should accept matching structs where one is more general than the other with respect to optional' do
struct1 = struct_t({'a'=>Integer, 'b'=>Integer, 'c'=>optional_t(Integer)})
struct2 = struct_t({'a'=>Integer, 'b'=>Integer, 'c'=>Integer})
expect(calculator.assignable?(struct1, struct2)).to eq(true)
end
it 'should reject matching structs where one is more special than the other with respect to optional' do
struct1 = struct_t({'a'=>Integer, 'b'=>Integer, 'c'=>Integer})
struct2 = struct_t({'a'=>Integer, 'b'=>Integer, 'c'=>optional_t(Integer)})
expect(calculator.assignable?(struct1, struct2)).to eq(false)
end
it 'should accept matching structs where one is more general than the other' do
struct1 = struct_t({'a'=>Integer, 'b'=>Integer})
struct2 = struct_t({'a'=>Numeric, 'b'=>Numeric})
expect(calculator.assignable?(struct1, struct2)).to eq(false)
expect(calculator.assignable?(struct2, struct1)).to eq(true)
end
it 'should accept matching hash' do
struct1 = struct_t({'a'=>Integer, 'b'=>Integer})
non_empty_string = constrained_string_t(range_t(1, nil))
hsh = hash_t(non_empty_string, Integer, range_t(2,2))
expect(calculator.assignable?(struct1, hsh)).to eq(true)
expect(calculator.assignable?(hsh, struct1)).to eq(true)
end
it 'should accept empty hash with key_type unit' do
struct1 = struct_t({'a'=>optional_t(Integer)})
hsh = hash_t(unit_t, unit_t, range_t(0, 0))
expect(calculator.assignable?(struct1, hsh)).to eq(true)
end
end
it 'should recognize ruby type inheritance' do
class Foo
end
class Bar < Foo
end
fooType = calculator.infer(Foo.new)
barType = calculator.infer(Bar.new)
expect(calculator.assignable?(fooType, fooType)).to eq(true)
expect(calculator.assignable?(Foo, fooType)).to eq(true)
expect(calculator.assignable?(fooType, barType)).to eq(true)
expect(calculator.assignable?(Foo, barType)).to eq(true)
expect(calculator.assignable?(barType, fooType)).to eq(false)
expect(calculator.assignable?(Bar, fooType)).to eq(false)
end
it 'should allow host class with same name' do
hc1 = TypeFactory.host_class('the_name')
hc2 = TypeFactory.host_class('the_name')
expect(calculator.assignable?(hc1, hc2)).to eq(true)
end
it 'should allow host class with name assigned to hostclass without name' do
hc1 = TypeFactory.host_class
hc2 = TypeFactory.host_class('the_name')
expect(calculator.assignable?(hc1, hc2)).to eq(true)
end
it 'should reject host classes with different names' do
hc1 = TypeFactory.host_class('the_name')
hc2 = TypeFactory.host_class('another_name')
expect(calculator.assignable?(hc1, hc2)).to eq(false)
end
it 'should reject host classes without name assigned to host class with name' do
hc1 = TypeFactory.host_class('the_name')
hc2 = TypeFactory.host_class
expect(calculator.assignable?(hc1, hc2)).to eq(false)
end
it 'should allow resource with same type_name and title' do
r1 = TypeFactory.resource('file', 'foo')
r2 = TypeFactory.resource('file', 'foo')
expect(calculator.assignable?(r1, r2)).to eq(true)
end
it 'should allow more specific resource assignment' do
r1 = TypeFactory.resource
r2 = TypeFactory.resource('file')
expect(calculator.assignable?(r1, r2)).to eq(true)
r2 = TypeFactory.resource('file', '/tmp/foo')
expect(calculator.assignable?(r1, r2)).to eq(true)
r1 = TypeFactory.resource('file')
expect(calculator.assignable?(r1, r2)).to eq(true)
end
it 'should reject less specific resource assignment' do
r1 = TypeFactory.resource('file', '/tmp/foo')
r2 = TypeFactory.resource('file')
expect(calculator.assignable?(r1, r2)).to eq(false)
r2 = TypeFactory.resource
expect(calculator.assignable?(r1, r2)).to eq(false)
end
context 'for TypeAlias, such that' do
let!(:parser) { TypeParser.singleton }
it 'it is assignable to the type that it is an alias for' do
t = type_alias_t('Alias', 'Integer').resolve(nil)
expect(calculator.assignable?(integer_t, t)).to be_truthy
end
it 'the type that it is an alias for is assignable to it' do
t = type_alias_t('Alias', 'Integer').resolve(nil)
expect(calculator.assignable?(t, integer_t)).to be_truthy
end
it 'a recursive alias can be assignable from a conformant type with any depth' do
scope = Object.new
t = type_alias_t('Tree', 'Hash[String,Variant[String,Tree]]')
loader = Object.new
loader.expects(:load).with(:type, 'tree').returns t
Adapters::LoaderAdapter.expects(:loader_for_model_object).at_least_once.returns loader
t.resolve(scope)
expect(calculator.assignable?(t, parser.parse('Hash[String,Variant[String,Hash[String,Variant[String,String]]]]'))).to be_truthy
end
it 'similar recursive aliases are assignable' do
scope = Object.new
t1 = type_alias_t('Tree1', 'Hash[String,Variant[String,Tree1]]')
t2 = type_alias_t('Tree2', 'Hash[String,Variant[String,Tree2]]')
loader = Object.new
loader.expects(:load).with(:type, 'tree1').returns t1
loader.expects(:load).with(:type, 'tree2').returns t2
Adapters::LoaderAdapter.expects(:loader_for_model_object).at_least_once.returns loader
t1.resolve(scope)
t2.resolve(scope)
expect(calculator.assignable?(t1, t2)).to be_truthy
end
it 'crossing recursive aliases are assignable' do
t1 = type_alias_t('Tree1', 'Hash[String,Variant[String,Tree2]]')
t2 = type_alias_t('Tree2', 'Hash[String,Variant[String,Tree1]]')
loader = Object.new
loader.expects(:load).with(:type, 'tree1').returns t1
loader.expects(:load).with(:type, 'tree2').returns t2
Adapters::LoaderAdapter.expects(:loader_for_model_object).at_least_once.returns loader
t1.resolve(loader)
t2.resolve(loader)
expect(calculator.assignable?(t1, t2)).to be_truthy
end
it 'Type[T] is assignable to Type[AT] when AT is an alias for T' do
scope = Object.new
ta = type_alias_t('PositiveInteger', 'Integer[0,default]')
loader = Object.new
loader.expects(:load).with(:type, 'positiveinteger').returns ta
Adapters::LoaderAdapter.expects(:loader_for_model_object).at_least_once.returns loader
t1 = type_t(range_t(0, :default))
t2 = parser.parse('Type[PositiveInteger]', scope)
expect(calculator.assignable?(t2, t1)).to be_truthy
end
it 'Type[T] is assignable to AT when AT is an alias for Type[T]' do
scope = Object.new
ta = type_alias_t('PositiveIntegerType', 'Type[Integer[0,default]]')
loader = Object.new
loader.expects(:load).with(:type, 'positiveintegertype').returns ta
Adapters::LoaderAdapter.expects(:loader_for_model_object).at_least_once.returns loader
t1 = type_t(range_t(0, :default))
t2 = parser.parse('PositiveIntegerType', scope)
expect(calculator.assignable?(t2, t1)).to be_truthy
end
it 'Type[Type[T]] is assignable to Type[Type[AT]] when AT is an alias for T' do
scope = Object.new
ta = type_alias_t('PositiveInteger', 'Integer[0,default]')
loader = Object.new
loader.expects(:load).with(:type, 'positiveinteger').returns ta
Adapters::LoaderAdapter.expects(:loader_for_model_object).at_least_once.returns loader
t1 = type_t(type_t(range_t(0, :default)))
t2 = parser.parse('Type[Type[PositiveInteger]]', scope)
expect(calculator.assignable?(t2, t1)).to be_truthy
end
it 'Type[Type[T]] is assignable to Type[AT] when AT is an alias for Type[T]' do
scope = Object.new
ta = type_alias_t('PositiveIntegerType', 'Type[Integer[0,default]]')
loader = Object.new
loader.expects(:load).with(:type, 'positiveintegertype').returns ta
Adapters::LoaderAdapter.expects(:loader_for_model_object).at_least_once.returns loader
t1 = type_t(type_t(range_t(0, :default)))
t2 = parser.parse('Type[PositiveIntegerType]', scope)
expect(calculator.assignable?(t2, t1)).to be_truthy
end
it 'An alias for a Type that describes an Iterable instance is assignable to Iterable' do
t = type_alias_t('MyType', 'Enum[a,b]').resolve(nil)
# True because String is iterable and an instance of Enum is a String
expect(calculator.assignable?(iterable_t, t)).to be_truthy
end
end
end
context 'when testing if x is instance of type t' do
include_context 'types_setup'
it 'should consider undef to be instance of Any, NilType, and optional' do
expect(calculator.instance?(PUndefType::DEFAULT, nil)).to eq(true)
expect(calculator.instance?(PAnyType::DEFAULT, nil)).to eq(true)
expect(calculator.instance?(POptionalType::DEFAULT, nil)).to eq(true)
end
it 'all types should be (ruby) instance of PAnyType' do
all_types.each do |t|
expect(t::DEFAULT.is_a?(PAnyType)).to eq(true)
end
end
it "should infer :undef to be Undef" do
expect(calculator.infer(:undef)).to be_assignable_to(undef_t)
end
it "should not consider :default to be instance of Runtime['ruby', 'Symbol]" do
expect(calculator.instance?(PRuntimeType.new(:ruby, 'Symbol'), :default)).to eq(false)
end
it "should not consider :undef to be instance of Runtime['ruby', 'Symbol]" do
expect(calculator.instance?(PRuntimeType.new(:ruby, 'Symbol'), :undef)).to eq(false)
end
it 'should consider :undef to be instance of an Optional type' do
expect(calculator.instance?(POptionalType::DEFAULT, :undef)).to eq(true)
end
it 'should not consider undef to be an instance of any other type than Any, Undef, Optional, and Init' do
types_to_test = all_types - [
PAnyType,
PUndefType,
POptionalType,
PInitType
]
types_to_test.each {|t| expect(calculator.instance?(t::DEFAULT, nil)).to eq(false) }
types_to_test.each {|t| expect(calculator.instance?(t::DEFAULT, :undef)).to eq(false) }
end
it 'should consider default to be instance of Default and Any' do
expect(calculator.instance?(PDefaultType::DEFAULT, :default)).to eq(true)
expect(calculator.instance?(PAnyType::DEFAULT, :default)).to eq(true)
end
it 'should not consider "default" to be an instance of anything but Default, Init, NotUndef, and Any' do
types_to_test = all_types - [
PAnyType,
PNotUndefType,
PDefaultType,
PInitType,
]
types_to_test.each {|t| expect(calculator.instance?(t::DEFAULT, :default)).to eq(false) }
end
it 'should consider integer instanceof PIntegerType' do
expect(calculator.instance?(PIntegerType::DEFAULT, 1)).to eq(true)
end
it 'should consider integer instanceof Integer' do
expect(calculator.instance?(Integer, 1)).to eq(true)
end
it 'should consider integer in range' do
range = range_t(0,10)
expect(calculator.instance?(range, 1)).to eq(true)
expect(calculator.instance?(range, 10)).to eq(true)
expect(calculator.instance?(range, -1)).to eq(false)
expect(calculator.instance?(range, 11)).to eq(false)
end
it 'should consider string in length range' do
range = constrained_string_t(range_t(1,3))
expect(calculator.instance?(range, 'a')).to eq(true)
expect(calculator.instance?(range, 'abc')).to eq(true)
expect(calculator.instance?(range, '')).to eq(false)
expect(calculator.instance?(range, 'abcd')).to eq(false)
end
it 'should consider string values' do
string = string_t('a')
expect(calculator.instance?(string, 'a')).to eq(true)
expect(calculator.instance?(string, 'c')).to eq(false)
end
it 'should consider array in length range' do
range = array_t(integer_t, range_t(1,3))
expect(calculator.instance?(range, [1])).to eq(true)
expect(calculator.instance?(range, [1,2,3])).to eq(true)
expect(calculator.instance?(range, [])).to eq(false)
expect(calculator.instance?(range, [1,2,3,4])).to eq(false)
end
it 'should consider hash in length range' do
range = hash_t(integer_t, integer_t, range_t(1,2))
expect(calculator.instance?(range, {1=>1})).to eq(true)
expect(calculator.instance?(range, {1=>1, 2=>2})).to eq(true)
expect(calculator.instance?(range, {})).to eq(false)
expect(calculator.instance?(range, {1=>1, 2=>2, 3=>3})).to eq(false)
end
it 'should consider collection in length range for array ' do
range = collection_t(range_t(1,3))
expect(calculator.instance?(range, [1])).to eq(true)
expect(calculator.instance?(range, [1,2,3])).to eq(true)
expect(calculator.instance?(range, [])).to eq(false)
expect(calculator.instance?(range, [1,2,3,4])).to eq(false)
end
it 'should consider collection in length range for hash' do
range = collection_t(range_t(1,2))
expect(calculator.instance?(range, {1=>1})).to eq(true)
expect(calculator.instance?(range, {1=>1, 2=>2})).to eq(true)
expect(calculator.instance?(range, {})).to eq(false)
expect(calculator.instance?(range, {1=>1, 2=>2, 3=>3})).to eq(false)
end
it 'should consider string matching enum as instanceof' do
enum = enum_t('XS', 'S', 'M', 'L', 'XL', '0')
expect(calculator.instance?(enum, 'XS')).to eq(true)
expect(calculator.instance?(enum, 'S')).to eq(true)
expect(calculator.instance?(enum, 'XXL')).to eq(false)
expect(calculator.instance?(enum, '')).to eq(false)
expect(calculator.instance?(enum, '0')).to eq(true)
expect(calculator.instance?(enum, 0)).to eq(false)
end
it 'should consider array[string] as instance of Array[Enum] when strings are instance of Enum' do
enum = enum_t('XS', 'S', 'M', 'L', 'XL', '0')
array = array_t(enum)
expect(calculator.instance?(array, ['XS', 'S', 'XL'])).to eq(true)
expect(calculator.instance?(array, ['XS', 'S', 'XXL'])).to eq(false)
end
it 'should consider array[mixed] as instance of Variant[mixed] when mixed types are listed in Variant' do
enum = enum_t('XS', 'S', 'M', 'L', 'XL')
sizes = range_t(30, 50)
array = array_t(variant_t(enum, sizes))
expect(calculator.instance?(array, ['XS', 'S', 30, 50])).to eq(true)
expect(calculator.instance?(array, ['XS', 'S', 'XXL'])).to eq(false)
expect(calculator.instance?(array, ['XS', 'S', 29])).to eq(false)
end
it 'should consider array[seq] as instance of Tuple[seq] when elements of seq are instance of' do
tuple = tuple_t(Integer, String, Float)
expect(calculator.instance?(tuple, [1, 'a', 3.14])).to eq(true)
expect(calculator.instance?(tuple, [1.2, 'a', 3.14])).to eq(false)
expect(calculator.instance?(tuple, [1, 1, 3.14])).to eq(false)
expect(calculator.instance?(tuple, [1, 'a', 1])).to eq(false)
end
context 'and t is Struct' do
it 'should consider hash[cont] as instance of Struct[cont-t]' do
struct = struct_t({'a'=>Integer, 'b'=>String, 'c'=>Float})
expect(calculator.instance?(struct, {'a'=>1, 'b'=>'a', 'c'=>3.14})).to eq(true)
expect(calculator.instance?(struct, {'a'=>1.2, 'b'=>'a', 'c'=>3.14})).to eq(false)
expect(calculator.instance?(struct, {'a'=>1, 'b'=>1, 'c'=>3.14})).to eq(false)
expect(calculator.instance?(struct, {'a'=>1, 'b'=>'a', 'c'=>1})).to eq(false)
end
it 'should consider empty hash as instance of Struct[x=>Optional[String]]' do
struct = struct_t({'a'=>optional_t(String)})
expect(calculator.instance?(struct, {})).to eq(true)
end
it 'should consider hash[cont] as instance of Struct[cont-t,optionals]' do
struct = struct_t({'a'=>Integer, 'b'=>String, 'c'=>optional_t(Float)})
expect(calculator.instance?(struct, {'a'=>1, 'b'=>'a'})).to eq(true)
end
it 'should consider hash[cont] as instance of Struct[cont-t,variants with optionals]' do
struct = struct_t({'a'=>Integer, 'b'=>String, 'c'=>variant_t(String, optional_t(Float))})
expect(calculator.instance?(struct, {'a'=>1, 'b'=>'a'})).to eq(true)
end
it 'should not consider hash[cont,cont2] as instance of Struct[cont-t]' do
struct = struct_t({'a'=>Integer, 'b'=>String})
expect(calculator.instance?(struct, {'a'=>1, 'b'=>'a', 'c'=>'x'})).to eq(false)
end
it 'should not consider hash[cont,cont2] as instance of Struct[cont-t,optional[cont3-t]' do
struct = struct_t({'a'=>Integer, 'b'=>String, 'c'=>optional_t(Float)})
expect(calculator.instance?(struct, {'a'=>1, 'b'=>'a', 'c'=>'x'})).to eq(false)
end
it 'should consider nil to be a valid element value' do
struct = struct_t({not_undef_t('a') => any_t, 'b'=>String})
expect(calculator.instance?(struct, {'a'=>nil , 'b'=>'a'})).to eq(true)
end
it 'should consider nil to be a valid element value but subject to value type' do
struct = struct_t({not_undef_t('a') => String, 'b'=>String})
expect(calculator.instance?(struct, {'a'=>nil , 'b'=>'a'})).to eq(false)
end
it 'should consider nil to be a valid element value but subject to value type even when key is optional' do
struct = struct_t({optional_t('a') => String, 'b'=>String})
expect(calculator.instance?(struct, {'a'=>nil , 'b'=>'a'})).to eq(false)
end
it 'should consider a hash where optional key is missing as assignable even if value of optional key is required' do
struct = struct_t({optional_t('a') => String, 'b'=>String})
expect(calculator.instance?(struct, {'b'=>'a'})).to eq(true)
end
end
context 'and t is Data' do
it 'undef should be considered instance of Data' do
expect(calculator.instance?(data_t, nil)).to eq(true)
end
it 'other symbols should not be considered instance of Data' do
expect(calculator.instance?(data_t, :love)).to eq(false)
end
it 'an empty array should be considered instance of Data' do
expect(calculator.instance?(data_t, [])).to eq(true)
end
it 'an empty hash should be considered instance of Data' do
expect(calculator.instance?(data_t, {})).to eq(true)
end
it 'a hash with nil/undef data should be considered instance of Data' do
expect(calculator.instance?(data_t, {'a' => nil})).to eq(true)
end
it 'a hash with nil/default key should not considered instance of Data' do
expect(calculator.instance?(data_t, {nil => 10})).to eq(false)
expect(calculator.instance?(data_t, {:default => 10})).to eq(false)
end
it 'an array with nil entries should be considered instance of Data' do
expect(calculator.instance?(data_t, [nil])).to eq(true)
end
it 'an array with nil + data entries should be considered instance of Data' do
expect(calculator.instance?(data_t, [1, nil, 'a'])).to eq(true)
end
end
context 'and t is something Callable' do
it 'a Closure should be considered a Callable' do
factory = Model::Factory
params = [factory.PARAM('a')]
the_block = factory.LAMBDA(params,factory.literal(42), nil).model
the_closure = Evaluator::Closure::Dynamic.new(:fake_evaluator, the_block, :fake_scope)
expect(calculator.instance?(all_callables_t, the_closure)).to be_truthy
expect(calculator.instance?(callable_t(any_t), the_closure)).to be_truthy
expect(calculator.instance?(callable_t(any_t, any_t), the_closure)).to be_falsey
end
it 'a Function instance should be considered a Callable' do
fc = Puppet::Functions.create_function(:foo) do
dispatch :foo do
param 'String', :a
end
def foo(a)
a
end
end
f = fc.new(:closure_scope, :loader)
# Any callable
expect(calculator.instance?(all_callables_t, f)).to be_truthy
# Callable[String]
expect(calculator.instance?(callable_t(String), f)).to be_truthy
end
end
context 'and t is a TypeAlias' do
let!(:parser) { TypeParser.singleton }
it 'should consider x an instance of the aliased simple type' do
t = type_alias_t('Alias', 'Integer').resolve(nil)
expect(calculator.instance?(t, 15)).to be_truthy
end
it 'should consider x an instance of the aliased parameterized type' do
t = type_alias_t('Alias', 'Integer[0,20]').resolve(nil)
expect(calculator.instance?(t, 15)).to be_truthy
end
it 'should consider t an instance of Iterable when aliased type is Iterable' do
t = type_alias_t('Alias', 'Enum[a, b]').resolve(nil)
expect(calculator.instance?(iterable_t, t)).to be_truthy
end
it 'should consider x an instance of the aliased type that uses self recursion' do
t = type_alias_t('Tree', 'Hash[String,Variant[String,Tree]]')
loader = Object.new
loader.expects(:load).with(:type, 'tree').returns t
Adapters::LoaderAdapter.expects(:loader_for_model_object).at_least_once.returns loader
t.resolve(loader)
expect(calculator.instance?(t, {'a'=>{'aa'=>{'aaa'=>'aaaa'}}, 'b'=>'bb'})).to be_truthy
end
it 'should consider x an instance of the aliased type that uses contains an alias that causes self recursion' do
t1 = type_alias_t('Tree', 'Hash[String,Variant[String,OtherTree]]')
t2 = type_alias_t('OtherTree', 'Hash[String,Tree]')
loader = Object.new
loader.expects(:load).with(:type, 'tree').returns t1
loader.expects(:load).with(:type, 'othertree').returns t2
Adapters::LoaderAdapter.expects(:loader_for_model_object).at_least_once.returns loader
t1.resolve(loader)
expect(calculator.instance?(t1, {'a'=>{'aa'=>{'aaa'=>'aaaa'}}, 'b'=>'bb'})).to be_truthy
end
end
end
context 'when converting a ruby class' do
it 'should yield \'PIntegerType\' for Fixnum' do
expect(calculator.type(Fixnum).class).to eq(PIntegerType)
end
it 'should yield \'PIntegerType\' for Bignum' do
expect(calculator.type(Bignum).class).to eq(PIntegerType)
end
it 'should yield \'PIntegerType\' for Integer' do
expect(calculator.type(Integer).class).to eq(PIntegerType)
end
it 'should yield \'PFloatType\' for Float' do
expect(calculator.type(Float).class).to eq(PFloatType)
end
it 'should yield \'PBooleanType\' for FalseClass and TrueClass' do
[FalseClass,TrueClass].each do |c|
expect(calculator.type(c).class).to eq(PBooleanType)
end
end
it 'should yield \'PUndefType\' for NilClass' do
expect(calculator.type(NilClass).class).to eq(PUndefType)
end
it 'should yield \'PStringType\' for String' do
expect(calculator.type(String).class).to eq(PStringType)
end
it 'should yield \'PRegexpType\' for Regexp' do
expect(calculator.type(Regexp).class).to eq(PRegexpType)
end
it 'should yield \'PArrayType[PAnyType]\' for Array' do
t = calculator.type(Array)
expect(t.class).to eq(PArrayType)
expect(t.element_type.class).to eq(PAnyType)
end
it 'should yield \'PHashType[PAnyType,PAnyType]\' for Hash' do
t = calculator.type(Hash)
expect(t.class).to eq(PHashType)
expect(t.key_type.class).to eq(PAnyType)
expect(t.value_type.class).to eq(PAnyType)
end
it 'type should yield \'PRuntimeType[ruby,Rational]\' for Rational' do
t = calculator.type(Rational)
expect(t.class).to eq(PRuntimeType)
expect(t.runtime).to eq(:ruby)
expect(t.runtime_type_name).to eq('Rational')
end
it 'infer should yield \'PRuntimeType[ruby,Rational]\' for Rational instance' do
t = calculator.infer(Rational(2, 3))
expect(t.class).to eq(PRuntimeType)
expect(t.runtime).to eq(:ruby)
expect(t.runtime_type_name).to eq('Rational')
end
end
context 'when processing meta type' do
it 'should infer PTypeType as the type of all other types' do
ptype = PTypeType
expect(calculator.infer(PUndefType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PScalarType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PScalarDataType::DEFAULT).is_a?(ptype)).to eq(true)
expect(calculator.infer(PStringType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PNumericType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PIntegerType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PFloatType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PRegexpType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PBooleanType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PCollectionType::DEFAULT).is_a?(ptype)).to eq(true)
expect(calculator.infer(PArrayType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PHashType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PIterableType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PRuntimeType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PClassType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PResourceType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PEnumType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PPatternType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PVariantType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PTupleType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(POptionalType::DEFAULT ).is_a?(ptype)).to eq(true)
expect(calculator.infer(PCallableType::DEFAULT ).is_a?(ptype)).to eq(true)
end
it 'should infer PTypeType as the type of all other types' do
expect(calculator.infer(PUndefType::DEFAULT ).to_s).to eq('Type[Undef]')
expect(calculator.infer(PScalarType::DEFAULT ).to_s).to eq('Type[Scalar]')
expect(calculator.infer(PScalarDataType::DEFAULT).to_s).to eq('Type[ScalarData]')
expect(calculator.infer(PStringType::DEFAULT ).to_s).to eq('Type[String]')
expect(calculator.infer(PNumericType::DEFAULT ).to_s).to eq('Type[Numeric]')
expect(calculator.infer(PIntegerType::DEFAULT ).to_s).to eq('Type[Integer]')
expect(calculator.infer(PFloatType::DEFAULT ).to_s).to eq('Type[Float]')
expect(calculator.infer(PRegexpType::DEFAULT ).to_s).to eq('Type[Regexp]')
expect(calculator.infer(PBooleanType::DEFAULT ).to_s).to eq('Type[Boolean]')
expect(calculator.infer(PCollectionType::DEFAULT).to_s).to eq('Type[Collection]')
expect(calculator.infer(PArrayType::DEFAULT ).to_s).to eq('Type[Array]')
expect(calculator.infer(PHashType::DEFAULT ).to_s).to eq('Type[Hash]')
expect(calculator.infer(PIterableType::DEFAULT ).to_s).to eq('Type[Iterable]')
expect(calculator.infer(PRuntimeType::DEFAULT ).to_s).to eq('Type[Runtime]')
expect(calculator.infer(PClassType::DEFAULT ).to_s).to eq('Type[Class]')
expect(calculator.infer(PResourceType::DEFAULT ).to_s).to eq('Type[Resource]')
expect(calculator.infer(PEnumType::DEFAULT ).to_s).to eq('Type[Enum]')
expect(calculator.infer(PVariantType::DEFAULT ).to_s).to eq('Type[Variant]')
expect(calculator.infer(PPatternType::DEFAULT ).to_s).to eq('Type[Pattern]')
expect(calculator.infer(PTupleType::DEFAULT ).to_s).to eq('Type[Tuple]')
expect(calculator.infer(POptionalType::DEFAULT ).to_s).to eq('Type[Optional]')
expect(calculator.infer(PCallableType::DEFAULT ).to_s).to eq('Type[Callable]')
expect(calculator.infer(PResourceType.new('foo::fee::fum')).to_s).to eq('Type[Foo::Fee::Fum]')
expect(calculator.infer(PResourceType.new('foo::fee::fum')).to_s).to eq('Type[Foo::Fee::Fum]')
expect(calculator.infer(PResourceType.new('Foo::Fee::Fum')).to_s).to eq('Type[Foo::Fee::Fum]')
end
it "computes the common type of PTypeType's type parameter" do
int_t = PIntegerType::DEFAULT
string_t = PStringType::DEFAULT
expect(calculator.infer([int_t]).to_s).to eq('Array[Type[Integer], 1, 1]')
expect(calculator.infer([int_t, string_t]).to_s).to eq('Array[Type[ScalarData], 2, 2]')
end
it 'should infer PTypeType as the type of ruby classes' do
class Foo
end
[Object, Numeric, Integer, Fixnum, Bignum, Float, String, Regexp, Array, Hash, Foo].each do |c|
expect(calculator.infer(c).is_a?(PTypeType)).to eq(true)
end
end
it 'should infer PTypeType as the type of PTypeType (meta regression short-circuit)' do
expect(calculator.infer(PTypeType::DEFAULT).is_a?(PTypeType)).to eq(true)
end
it 'computes instance? to be true if parameterized and type match' do
int_t = PIntegerType::DEFAULT
type_t = TypeFactory.type_type(int_t)
type_type_t = TypeFactory.type_type(type_t)
expect(calculator.instance?(type_type_t, type_t)).to eq(true)
end
it 'computes instance? to be false if parameterized and type do not match' do
int_t = PIntegerType::DEFAULT
string_t = PStringType::DEFAULT
type_t = TypeFactory.type_type(int_t)
type_t2 = TypeFactory.type_type(string_t)
type_type_t = TypeFactory.type_type(type_t)
# i.e. Type[Integer] =~ Type[Type[Integer]] # false
expect(calculator.instance?(type_type_t, type_t2)).to eq(false)
end
it 'computes instance? to be true if unparameterized and matched against a type[?]' do
int_t = PIntegerType::DEFAULT
type_t = TypeFactory.type_type(int_t)
expect(calculator.instance?(PTypeType::DEFAULT, type_t)).to eq(true)
end
end
context 'when asking for an iterable ' do
it 'should produce an iterable for an Integer range that is finite' do
t = PIntegerType.new(1, 10)
expect(calculator.iterable(t).respond_to?(:each)).to eq(true)
end
it 'should not produce an iterable for an Integer range that has an infinite side' do
t = PIntegerType.new(nil, 10)
expect(calculator.iterable(t)).to eq(nil)
t = PIntegerType.new(1, nil)
expect(calculator.iterable(t)).to eq(nil)
end
it 'all but Integer range are not iterable' do
[Object, Numeric, Float, String, Regexp, Array, Hash].each do |t|
expect(calculator.iterable(calculator.type(t))).to eq(nil)
end
end
it 'should produce an iterable for a type alias of an Iterable type' do
t = PTypeAliasType.new('MyAlias', nil, PIntegerType.new(1, 10))
expect(calculator.iterable(t).respond_to?(:each)).to eq(true)
end
end
context 'when dealing with different types of inference' do
it 'an instance specific inference is produced by infer' do
expect(calculator.infer(['a','b']).element_type.values).to eq(['a', 'b'])
end
it 'a generic inference is produced using infer_generic' do
expect(calculator.infer_generic(['a','b']).element_type).to eql(string_t(range_t(1,1)))
end
it 'a generic result is created by generalize given an instance specific result for an Array' do
generic = calculator.infer(['a','b'])
expect(generic.element_type.values).to eq(['a','b'])
generic = generic.generalize
expect(generic.element_type).to eql(string_t(range_t(1,1)))
end
it 'a generic result is created by generalize given an instance specific result for a Hash' do
generic = calculator.infer({'a' =>1,'bcd' => 2})
expect(generic.key_type.values.sort).to eq(['a', 'bcd'])
expect(generic.value_type.from).to eq(1)
expect(generic.value_type.to).to eq(2)
generic = generic.generalize
expect(generic.key_type.size_type).to eq(range_t(1,3))
expect(generic.value_type.from).to eq(nil)
expect(generic.value_type.to).to eq(nil)
end
it 'ensures that Struct key types are not generalized' do
generic = struct_t({'a' => any_t}).generalize
expect(generic.to_s).to eq("Struct[{'a' => Any}]")
generic = struct_t({not_undef_t('a') => any_t}).generalize
expect(generic.to_s).to eq("Struct[{NotUndef['a'] => Any}]")
generic = struct_t({optional_t('a') => string_t}).generalize
expect(generic.to_s).to eq("Struct[{Optional['a'] => String}]")
end
it 'ensures that Struct value types are generalized' do
generic = struct_t({'a' => range_t(1, 3)}).generalize
expect(generic.to_s).to eq("Struct[{'a' => Integer}]")
end
it "does not reduce by combining types when using infer_set" do
element_type = calculator.infer(['a','b',1,2]).element_type
expect(element_type.class).to eq(PScalarDataType)
inferred_type = calculator.infer_set(['a','b',1,2])
expect(inferred_type.class).to eq(PTupleType)
element_types = inferred_type.types
expect(element_types[0].class).to eq(PStringType)
expect(element_types[1].class).to eq(PStringType)
expect(element_types[2].class).to eq(PIntegerType)
expect(element_types[3].class).to eq(PIntegerType)
end
it 'does not reduce by combining types when using infer_set and values are undef' do
element_type = calculator.infer(['a',nil]).element_type
expect(element_type.class).to eq(PStringType)
inferred_type = calculator.infer_set(['a',nil])
expect(inferred_type.class).to eq(PTupleType)
element_types = inferred_type.types
expect(element_types[0].class).to eq(PStringType)
expect(element_types[1].class).to eq(PUndefType)
end
it 'infers on an empty Array produces Array[Unit,0,0]' do
inferred_type = calculator.infer([])
expect(inferred_type.element_type.class).to eq(PUnitType)
expect(inferred_type.size_range).to eq([0, 0])
end
it 'infer_set on an empty Array produces Array[Unit,0,0]' do
inferred_type = calculator.infer_set([])
expect(inferred_type.element_type.class).to eq(PUnitType)
expect(inferred_type.size_range).to eq([0, 0])
end
end
context 'when determening callability' do
context 'and given is exact' do
it 'with callable' do
required = callable_t(string_t)
given = callable_t(string_t)
expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args tuple' do
required = callable_t(string_t)
given = tuple_t(string_t)
expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args tuple having a block' do
required = callable_t(string_t, callable_t(string_t))
given = tuple_t(string_t, callable_t(string_t))
expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args array' do
required = callable_t(string_t)
given = array_t(string_t, range_t(1, 1))
expect(calculator.callable?(required, given)).to eq(true)
end
end
context 'and given is more generic' do
it 'with callable' do
required = callable_t(string_t)
given = callable_t(any_t)
expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args tuple' do
required = callable_t(string_t)
given = tuple_t(any_t)
expect(calculator.callable?(required, given)).to eq(false)
end
it 'with args tuple having a block' do
required = callable_t(string_t, callable_t(string_t))
given = tuple_t(string_t, callable_t(any_t))
expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args tuple having a block with captures rest' do
required = callable_t(string_t, callable_t(string_t))
given = tuple_t(string_t, callable_t(any_t, 0, :default))
expect(calculator.callable?(required, given)).to eq(true)
end
end
context 'and given is more specific' do
it 'with callable' do
required = callable_t(any_t)
given = callable_t(string_t)
expect(calculator.callable?(required, given)).to eq(false)
end
it 'with args tuple' do
required = callable_t(any_t)
given = tuple_t(string_t)
expect(calculator.callable?(required, given)).to eq(true)
end
it 'with args tuple having a block' do
required = callable_t(string_t, callable_t(any_t))
given = tuple_t(string_t, callable_t(string_t))
expect(calculator.callable?(required, given)).to eq(false)
end
it 'with args tuple having a block with captures rest' do
required = callable_t(string_t, callable_t(any_t))
given = tuple_t(string_t, callable_t(string_t, 0, :default))
expect(calculator.callable?(required, given)).to eq(false)
end
end
end
matcher :be_assignable_to do |type|
match do |actual|
type.is_a?(PAnyType) && type.assignable?(actual)
end
failure_message do |actual|
"#{TypeFormatter.string(actual)} should be assignable to #{TypeFormatter.string(type)}"
end
failure_message_when_negated do |actual|
"#{TypeFormatter.string(actual)} is assignable to #{TypeFormatter.string(type)} when it should not"
end
end
end
end
end
| 38.680749 | 145 | 0.649098 |
4a936fd9eadf7266e6eeda9dd57bd78ba7af8efa | 828 | # frozen_string_literal: true
require 'rexml/document'
actions :create, :delete, :create_if_missing
default_action :create
attribute :name, kind_of: String, name_attribute: true
attribute :retry_count, kind_of: Integer
attribute :timeout, kind_of: Integer
attribute :username, kind_of: String
attribute :domain, kind_of: String
attribute :password, kind_of: String
# 'begin' => 'IP', 'end' => 'IP'
attribute :ranges, kind_of: Hash
# Array of IP address strings
attribute :specifics, kind_of: Array
# Array of IPLIKE address strings ([0-9]{1,3}((,|-)[0-9]{1,3})*|\*)\.([0-9]{1,3}((,|-)[0-9]{1,3})*|\*)\.([0-9]{1,3}((,|-)[0-9]{1,3})*|\*)\.([0-9]{1,3}((,|-)[0-9]{1,3})*|\*)
attribute :ip_matches, kind_of: Array
attribute :position, kind_of: String, equal_to: %w(top bottom), default: 'bottom'
attr_accessor :exists, :different
| 37.636364 | 172 | 0.684783 |
4a0d845dfed86f445b4c67daecdd2d78cc8524a6 | 140 | class AddGoldOnLeftToTournaments < ActiveRecord::Migration[5.1]
def change
add_column :tournaments, :gold_on_left, :boolean
end
end
| 23.333333 | 63 | 0.778571 |
f717d30d0b78de1b620318329fa7dd5659d6be54 | 18,946 | require 'active_support/logger'
namespace :shf do
ACCEPTED_STATE = 'accepted' unless defined?(ACCEPTED_STATE)
LOG_FILE = 'log/shf_tasks.log' unless defined?(LOG_FILE)
# TODO removed shf:dinkurs_load task once response condition (DinkursFetch) is deployed
desc 'load Dinkurs events for companies'
task :dinkurs_load => [:environment] do
LOG = 'log/dinkurs_load_events.log'
ActivityLogger.open(LOG, 'SHF_TASK', 'Load Dinkurs Events') do |log|
Company.where.not(dinkurs_company_id: [nil, '']).order(:id).each do |company|
company.fetch_dinkurs_events
company.reload
log.record('info', "Company #{company.id}: #{company.events.count} events.")
end
end
end
desc 'prepare db (current env): drop, setup, migrate, create baseline data.'
task db_prep: [:environment] do
Rake::Task['db:drop'].invoke if database_exists?
tasks = ['db:create', 'db:migrate', 'db:test:prepare',
'shf:load_regions', 'shf:load_kommuns',
'shf:load_file_delivery_methods']
tasks.each { |t| Rake::Task[t].invoke }
puts "\n DB is created with baseline data.\n"
puts "\n Be sure to run 'rails db:seed' if you need seed data. \n\n"
end
# @desc rails/rake task that runs cucumber using the 'shf_core_only' profile
# (which is defined in config/cucumber.yml)
#
# @usage pass arguments from the command line as a string in an array:
# bundle exec rails shf:cuke_core_only['features/user_account']
# will run only the features in the features/user_account directory
# bundle exec rails shf:cuke_core_only['--format html features/user_account']
# will use the html format and run only the features in the features/user_account directory
#
desc "run Cucumber 'core' features only.Pass in other cucumber args as one string.(skip db_seeding, conditions, selenium_browser). [shf_core profile in config/cucumber.yml]"
task :cuke_core_only, [:cucumber_args_as_a_string] => [:environment] do | _task, task_args |
require 'cucumber/rake/task'
usage = "\nshf:cuke_core_only runs the cucumber profile 'shf_core', which excludes 'non-core' and long-running features.\n shf_core is defined in config/cucumber.yml\n\n USAGE: rails shf:cuke_core_only['<any options for cucumber here>']\n Ex: rails shf:cuke_core_only['--format html features/user_account']\n"
t_args = task_args[:cucumber_args_as_a_string]
if t_args == '--help' || t_args == '-H' || t_args == 'h'
puts usage
else
Cucumber::Rake::Task.new('shf_core_only_cuke_task', 'Run only the SHF core features') do |cuke_t|
cuke_t.cucumber_opts = t_args
cuke_t.profile = 'shf_core'
end
Rake::Task[:shf_core_only_cuke_task].invoke
end
end
desc "import membership apps from csv file. Provide the full filename (with path)"
task :import_membership_apps, [:csv_filename] => [:environment] do |t, args|
require 'csv'
require 'smarter_csv'
usage = 'rake shf:import_membership_apps["./spec/fixtures/test-import-files/member-companies-sanitized-small.csv"]'
DEFAULT_PASSWORD = 'whatever'
headers_to_columns_mapping = {
membership_number: :membership_number,
email: :email,
company_number: :company_number,
first_name: :first_name,
last_name: :last_name,
company_name: :company_name,
street: :street,
post_code: :post_code,
stad: :city,
region: :region,
phone_number: :phone_number,
website: :website,
category1: :category1,
category2: :category2
}
csv_options = {
col_sep: ';',
headers_in_file: true,
remove_empty_values: false,
remove_zero_values: false,
file_encoding: 'UTF-8',
key_mapping: headers_to_columns_mapping
}
log = ActivityLogger.open(LOG_FILE, 'SHF_TASK', 'Import CSV')
if args.has_key? :csv_filename
if File.exist? args[:csv_filename]
csv = SmarterCSV.process(args[:csv_filename], csv_options)
#csv = CSV.parse(csv_text, :headers => true, :encoding => 'ISO-8859-1')
num_read = 0
error_rows = 0
csv.each do |row|
begin
import_a_member_app_csv(row, log)
num_read += 1
rescue ActiveRecord::RecordInvalid => invalid_info
error_rows += 1
log.record('error', "#{invalid_info.record.errors.full_messages.join(", ")}")
end
end
msg = "\nRead #{num_read + error_rows} rows.\n" +
"#{num_read} were valid and their information was imported.\n" +
"#{error_rows} had errors."
log.record('info', msg)
else
log.record('error', "#{args[:csv_filename]} does not exist. Nothing imported")
log.close
raise LoadError
end
else
msg = "You must specify a .csv filename to import.\n Ex: #{usage}"
log.record('error', msg)
log.close
raise "ERROR: You must specify a .csv filename to import. Ex: #{usage}"
end
log.close
end
desc "load regions data (counties plus 'Sverige' and 'Online')"
task :load_regions => [:environment] do
# NOTE: This is now accomplished with the Seeder::RegionsSeeder
ActivityLogger.open(LOG_FILE, 'SHF_TASK', 'Load Regions') do |log|
# Populate the 'regions' table for Swedish regions (aka counties),
# as well as 'Sverige' (Sweden) and 'Online'. This is used to specify
# the primary region in which a company operates.
#
# This uses the 'city-state' gem for a list of regions (name and ISO code).
if Region.exists?
log.record('warn', 'Regions table not empty.')
else
CS.states(:se).each_pair { |k, v| Region.create(name: v, code: k.to_s) }
Region.create(name: 'Sverige', code: nil)
Region.create(name: 'Online', code: nil)
log.record('info', "#{Region.count} Regions created.")
end
end
end
desc "load kommuns data (290 Swedish municipalities)"
task :load_kommuns => [:environment] do
# NOTE: This is now accomplished with the Seeder::KommunsSeeder
require 'csv'
require 'smarter_csv'
ActivityLogger.open(LOG_FILE, 'SHF_TASK', 'Load Kommuns') do |log|
if Kommun.exists?
log.record('warn', 'Kommuns table not empty.')
else
SmarterCSV.process('lib/seeds/kommuner.csv').each do |kommun|
Kommun.create(name: kommun[:name])
end
log.record('info', "#{Kommun.count} Kommuns created.")
end
end
end
desc "Initialize app file delivery methods"
task load_file_delivery_methods: :environment do
# NOTE: This is now accomplished with the Seeder::FileDeliveryMethodsSeeder
log_file = 'log/load_file_delivery_methods.log'
ActivityLogger.open(log_file, 'App Files', 'set delivery methods') do |log|
if AdminOnly::FileDeliveryMethod.exists?
log.record('warn', 'FileDeliveryMethod table not empty.')
next # break out of rake task
end
delivery_methods = [
{ name: AdminOnly::FileDeliveryMethod::METHOD_NAMES[:upload_now],
description_sv: 'Ladda upp nu',
description_en: 'Upload now',
default_option: true },
{ name: AdminOnly::FileDeliveryMethod::METHOD_NAMES[:upload_later],
description_sv: 'Ladda upp senare',
description_en: 'Upload later' },
{ name: AdminOnly::FileDeliveryMethod::METHOD_NAMES[:email],
description_sv: 'Skicka via e-post',
description_en: 'Send via email' },
{ name: AdminOnly::FileDeliveryMethod::METHOD_NAMES[:mail],
description_sv: 'Skicka via vanlig post',
description_en: 'Send via regular mail' },
{ name: AdminOnly::FileDeliveryMethod::METHOD_NAMES[:files_uploaded],
description_sv: 'Alla filer är uppladdade',
description_en: 'All files are uploaded' }
]
delivery_methods.each do |rec|
AdminOnly::FileDeliveryMethod.create!(rec)
end
log.record('info', "Created #{delivery_methods.size} records.")
end
end
# Geocode all Addresses.
# arguments:
# sleep: number of seconds to sleep between each geocode request so we
# don't exceed the number of requests per <x> seconds
# for Google (or any other service)
# Note that 1 Address may require multiple geocode requests
# to get a valid locataion if the Address is a 'fake' address.
# See the note below about using :geocode_best_possible
# default = 0.2 seconds
#
# batch_num: number of objects in each batch (also so we don't exceed
# the number of requests per second)
# default = 50
#
# We don't use the geocode:all rake task
# because we want to call the :geocode_best_possible method instead of
# just using the 'geocoded_by :entire_address' that the geocode:all task
# would use. We do this because the fake data generated might not
# create a real address, so the :entire_address might not really give us
# the geolocation (latitude, longitude) info.
#
# This is based on the Geocoder gem geocode:all task.
# @see https://github.com/alexreisner/geocoder#bulk-geocoding for more info
#
# We don't want to exceed the limit of number of geocoding calls per second
# (see the Google maps API limits). We're using the free, standard plan
# as of 2017-03-29, which means 50 requests per second.
#
# Examples:
# use the defaults:
# rake shf:geolocate_all_addresses
#
# set the number of seconds to sleep between geocoding requests to 3 seconds:
# rake shf:geolocate_all_addresses[3]
#
# set the number of records to request in each batch to 19, and number of seconds to sleep = 3:
# rake shf:geolocate_all_addresses[3, 19]
#
# Note that there are NO SPACES after the commas (between the arguments)
#
desc "geocode all addresses args=[sleep_time=2,batch_num=40] (those without latitude, longitude info) NO SPACES between arguments"
task :geocode_all_addresses, [:sleep_time, :batch_num] => :environment do |_task_name, args|
args = args.with_defaults(sleep_time: 0.2, batch_num: 50)
Geocoder.configure(timeout: 20) # geocoding service timeout (secs)
ActivityLogger.open(LOG_FILE, 'SHF_TASK', 'Geocode Addresses') do |log|
not_geocoded = Address.not_geocoded
msg = " #{not_geocoded.count} Addresses are not yet geocoded. Will geocode."
log.record('info', msg)
Address.geocode_all_needed(sleep_between: args[:sleep_time].to_f, num_per_batch: args[:batch_num].to_i)
msg = " After running Address.geocode_all_needed(sleep_between: " +
"#{args[:sleep_time].to_f}, num_per_batch: #{args[:batch_num].to_i})" +
", #{Address.not_geocoded.count} Addresses are not geocoded."
log.record('info', msg)
end
end
MEMBER_PAGES_PATH = File.join(Rails.root, 'app', 'views', 'pages') unless defined?(MEMBER_PAGES_PATH)
desc 'add member page arg=[filename]'
task :add_member_page, [:filename] => :environment do |task_name, args|
ActivityLogger.open(LogfileNamer.name_for(MemberPage), 'SHF_TASK', task_name) do |log|
filename = filename_from_args(args, log)
if filename =~ /[^\w\-\.]/
log.record('error', "Unacceptable characters in filename: #{filename}")
log.record('error', "Acceptable characters are a-z, A-Z, 0-9, '_', '-' and '.'")
raise 'ERROR: Unacceptable filename'
end
# Add html file type if not present
filename = filename + '.html' unless filename =~ /.*\.html$/
filepath = File.join(MEMBER_PAGES_PATH, filename)
unless File.file?(filepath)
begin
File.new(filepath, 'w+')
log.record('info', "Created member page file: #{filename}")
rescue
log.record('error', "Cannot create file: #{filename}")
raise
end
else
log.record('error', 'File already exists in pages directory')
raise 'ERROR: File already exists in pages directory'
end
end
end
desc 'delete a member page arg=[filename] (deletes the file from the filesystem)'
task :delete_member_page, [:filename] => :environment do |task_name, args|
ActivityLogger.open(LogfileNamer.name_for(MemberPage), 'SHF_TASK', task_name) do |log|
filename = filename_from_args(args, log)
member_page_abspath = File.expand_path(File.join(MEMBER_PAGES_PATH, filename))
if File.exist?(member_page_abspath)
begin
File.delete(member_page_abspath)
log.info( "Member Page file deleted: #{member_page_abspath}")
rescue => e
log.error( "Unable to delete #{member_page_abspath}. Error: #{e}")
raise e
end
else
error_msg = "Member page file not found: #{member_page_abspath}"
log.error( error_msg)
raise error_msg
end
end
end
def filename_from_args(args, log)
args.fetch(:filename) do |_key|
error_message = 'No filename given. You must specify a file name.'
log.error(error_message)
raise "ERROR: #{error_message}"
end
end
# Create one org num: "rake shf:orgnum"
# Create 5 org nums: "rake shf:orgnum[5]"
desc "Create one or more unused Swedish Organization Numbers (aka 'company numbers' in SHF)"
task :orgnum, [:how_many] => :environment do |_task_name, args|
how_many = args.with_defaults(how_many: 1)[:how_many].to_i
puts "\n#{how_many} available Org (Company) #{'Number'.pluralize(how_many)}: \n\n"
how_many.times do
puts create_one_unused_org_number
end
puts "\n"
end
namespace :seed do
# This task is needed until we upgrade to Rails 6, which has the db:seed:replant task
desc 'Delete all SHF data (excluding Rails internal tables) via TRUNCATE statement. Helpful for reseeding'
task replant: :environment do
if database_exists?
rails_internal_tables = %w(ar_internal_metadata schema_migrations)
connection = ActiveRecord::Base.connection
tablenames = connection.tables - rails_internal_tables
connection.disable_referential_integrity do
tablenames.each { |table_name| connection.exec_query "TRUNCATE TABLE \"#{table_name}\" CASCADE" }
end
end
end
end
# -------------------------------------------------
def create_one_unused_org_number
org_number = nil
100.times do
org_number = OrgNummersGenerator.generate_one
# stop if number is available (not used)
break if !Company.find_by_company_number(org_number)
end
org_number
end
def database_exists?
ActiveRecord::Base.connection
rescue ActiveRecord::NoDatabaseError
false
else
true
end
def import_a_member_app_csv(row, log)
log.record('info', "Importing row: #{row.inspect}")
# log_and_show log, Logger::INFO, "Importing row: #{row.inspect}"
if (user = User.find_by(email: row[:email]))
puts_already_exists 'User', row[:email]
else
user = User.create!(email: row[:email], password: DEFAULT_PASSWORD)
puts_created 'User', row[:email]
end
company = find_or_create_company(row[:company_number], user.email,
name: row[:company_name],
street: row[:street],
post_code: row[:post_code],
city: row[:city],
region: row[:region],
phone_number: row[:phone_number],
website: row[:website])
if (membership = ShfApplication.find_by(user: user.id))
puts_already_exists('Membership application', " org number: #{row[:company_number]}")
else
membership = ShfApplication.create!(company_number: row[:company_number],
first_name: row[:first_name],
last_name: row[:last_name],
contact_email: user.email,
state: ACCEPTED_STATE,
membership_number: row[:membership_number],
user: user,
company: company
)
puts_created('Membership application', " org number: #{row[:company_number]}")
end
membership = find_or_create_category(row[:category1], membership) unless row[:category1].nil?
membership = find_or_create_category(row[:category2], membership) unless row[:category2].nil?
membership.save!
if membership.accepted?
membership.company = company
user.save!
end
end
def find_or_create_category(category_name, membership)
category = BusinessCategory.find_by_name(category_name)
if category
puts_already_exists 'Category', "#{category_name}"
else
category = BusinessCategory.create!(name: category_name)
puts_created 'Category', "#{category_name}"
end
membership.business_categories << category
membership
end
def find_or_create_company(company_num, email,
name:,
street:,
post_code:,
city:,
region:,
phone_number:,
website:)
company = Company.find_by_company_number(company_num)
if company
puts_already_exists 'Company', "#{company_num}"
else
region = Region.find_by name: region
Company.create!(company_number: company_num,
email: email,
name: name,
phone_number: phone_number,
website: website)
company = Company.find_by_company_number(company_num)
company.addresses << Address.new(street_address: street,
post_code: post_code,
city: city,
region: region)
puts_created 'Company', company.company_number
end
company
end
def puts_created(item_type, item_name)
puts " #{item_type} created and saved: #{item_name}"
end
def puts_already_exists(item_type, item_name)
puts " #{item_type} already exists: #{item_name}"
end
def puts_error_creating(item_type, item_name)
puts " ERROR: Could not create #{item_type} #{item_name}. Skipped"
end
end
| 33.592199 | 316 | 0.627573 |
287fc397151c28256f01f60ad774b2b5c95973c0 | 264 | require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
RSpec.configure do |config|
# == Truncate database after suite
#
config.before :suite do
DatabaseCleaner.clean
end
# == gem mongoid-rspec
#
config.include Mongoid::Matchers
end
| 16.5 | 38 | 0.727273 |
1a54ef93ed815ddb868094648fc6022282986e57 | 192 | module Backend
module PaginationHelper
def udongo_paginate(collection, options = {})
will_paginate(collection, Udongo::WillPaginate::Options.new(options).values)
end
end
end
| 24 | 82 | 0.744792 |
e9e25e7271af6083a0e874ee66e140c88a131bc6 | 156 | Rails.autoloaders.each do |autoloader|
autoloader.inflector.inflect(
'gov_uk_helper' => 'GovUKHelper',
'update_fc_data' => 'UpdateFCData'
)
end
| 22.285714 | 38 | 0.711538 |
bf25a8e04d77c39ab33e71547743388debeeb5c0 | 3,760 | require 'rails_helper'
RSpec.describe SendReplyJob, type: :job do
subject(:job) { described_class.perform_later(message) }
let(:message) { create(:message) }
it 'enqueues the job' do
expect { job }.to have_enqueued_job(described_class)
.with(message)
.on_queue('high')
end
context 'when the job is triggered on a new message' do
let(:process_service) { double }
before do
allow(process_service).to receive(:perform)
end
it 'calls Facebook::SendOnFacebookService when its facebook message' do
facebook_channel = create(:channel_facebook_page)
facebook_inbox = create(:inbox, channel: facebook_channel)
message = create(:message, conversation: create(:conversation, inbox: facebook_inbox))
allow(Facebook::SendOnFacebookService).to receive(:new).with(message: message).and_return(process_service)
expect(Facebook::SendOnFacebookService).to receive(:new).with(message: message)
expect(process_service).to receive(:perform)
described_class.perform_now(message.id)
end
it 'calls ::Twitter::SendOnTwitterService when its twitter message' do
twitter_channel = create(:channel_twitter_profile)
twitter_inbox = create(:inbox, channel: twitter_channel)
message = create(:message, conversation: create(:conversation, inbox: twitter_inbox))
allow(::Twitter::SendOnTwitterService).to receive(:new).with(message: message).and_return(process_service)
expect(::Twitter::SendOnTwitterService).to receive(:new).with(message: message)
expect(process_service).to receive(:perform)
described_class.perform_now(message.id)
end
it 'calls ::Twilio::SendOnTwilioService when its twilio message' do
twilio_channel = create(:channel_twilio_sms)
message = create(:message, conversation: create(:conversation, inbox: twilio_channel.inbox))
allow(::Twilio::SendOnTwilioService).to receive(:new).with(message: message).and_return(process_service)
expect(::Twilio::SendOnTwilioService).to receive(:new).with(message: message)
expect(process_service).to receive(:perform)
described_class.perform_now(message.id)
end
it 'calls ::Telegram::SendOnTelegramService when its telegram message' do
telegram_channel = create(:channel_telegram)
message = create(:message, conversation: create(:conversation, inbox: telegram_channel.inbox))
allow(::Telegram::SendOnTelegramService).to receive(:new).with(message: message).and_return(process_service)
expect(::Telegram::SendOnTelegramService).to receive(:new).with(message: message)
expect(process_service).to receive(:perform)
described_class.perform_now(message.id)
end
it 'calls ::Line:SendOnLineService when its line message' do
line_channel = create(:channel_line)
message = create(:message, conversation: create(:conversation, inbox: line_channel.inbox))
allow(::Line::SendOnLineService).to receive(:new).with(message: message).and_return(process_service)
expect(::Line::SendOnLineService).to receive(:new).with(message: message)
expect(process_service).to receive(:perform)
described_class.perform_now(message.id)
end
it 'calls ::Whatsapp:SendOnWhatsappService when its line message' do
whatsapp_channel = create(:channel_whatsapp)
message = create(:message, conversation: create(:conversation, inbox: whatsapp_channel.inbox))
allow(::Whatsapp::SendOnWhatsappService).to receive(:new).with(message: message).and_return(process_service)
expect(::Whatsapp::SendOnWhatsappService).to receive(:new).with(message: message)
expect(process_service).to receive(:perform)
described_class.perform_now(message.id)
end
end
end
| 48.205128 | 114 | 0.736436 |
4a8184f4628effd83fb652fc93230616017db67a | 1,172 | module Kublog
module XhrUpload
module FileHelper
protected
# Gets the file received throug Rack Environment
def received_file
if env['rack.input']
make_tempfile(env['rack.input'], :filename => env['HTTP_X_FILE_NAME'], :type => env["CONTENT_TYPE"])
end
end
# Taken from rack. Follows the example of maca to create a TempFile
# via XHR Request. Used to asynchronously upload images
def make_tempfile(input, options = {})
tempfile = Tempfile.new('image-upload')
tempfile.set_encoding(Encoding::BINARY) if tempfile.respond_to?(:set_encoding)
tempfile.binmode
buffer = ""
while input.read(1024 * 4, buffer)
entire_buffer_written_out = false
while !entire_buffer_written_out
written = tempfile.write(buffer)
entire_buffer_written_out = written == Rack::Utils.bytesize(buffer)
if !entire_buffer_written_out
buffer.slice!(0 .. written - 1)
end
end
end
tempfile.rewind
{:tempfile => tempfile}.merge(options)
end
end
end
end | 32.555556 | 110 | 0.612628 |
08f6a54776f7d4f32ae95c7005b9884bbf43f865 | 1,446 | module Gitlab
class ProjectTemplate
attr_reader :title, :name, :description, :preview
def initialize(name, title, description, preview)
@name, @title, @description, @preview = name, title, description, preview
end
alias_method :logo, :name
def file
archive_path.open
end
def archive_path
Rails.root.join("vendor/project_templates/#{name}.tar.gz")
end
def clone_url
"https://gitlab.com/gitlab-org/project-templates/#{name}.git"
end
def ==(other)
name == other.name && title == other.title
end
TEMPLATES_TABLE = [
ProjectTemplate.new('rails', 'Ruby on Rails', 'Includes an MVC structure, Gemfile, Rakefile, along with many others, to help you get started.', 'https://gitlab.com/gitlab-org/project-templates/rails'),
ProjectTemplate.new('spring', 'Spring', 'Includes an MVC structure, mvnw and pom.xml to help you get started.', 'https://gitlab.com/gitlab-org/project-templates/spring'),
ProjectTemplate.new('express', 'NodeJS Express', 'Includes an MVC structure to help you get started.', 'https://gitlab.com/gitlab-org/project-templates/express')
].freeze
class << self
def all
TEMPLATES_TABLE
end
def find(name)
all.find { |template| template.name == name.to_s }
end
def archive_directory
Rails.root.join("vendor_directory/project_templates")
end
end
end
end
| 30.125 | 207 | 0.666667 |
1a0afea1e7812eb3ecc364f0b554f8e73a8a64f8 | 1,014 | module SessionsHelper
# 渡されたユーザーでログインする
def log_in(user)
session[:user_id] = user.id
end
# ユーザーのセッションを永続的にする
def remember(user)
user.remember # => DB: remember_digest
cookies.permanent.signed[:user_id] = user.id # signedでuser_idを暗号化
cookies.permanent[:remember_token] = user.remember_token
end
# 記憶トークン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?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end
# ユーザーがログインしていればtrue、その他ならfalseを返す
def logged_in?
!current_user.nil?
end
# 永続的セッションを破棄する
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
# 現在のユーザーをログアウトする
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
end
| 22.043478 | 70 | 0.686391 |
e2ba9921a93dcb273249424a696667726754f22c | 995 | #!/usr/bin/env ruby
require 'webrick'
require 'webrick/https'
require 'openssl'
private_key_file = File.expand_path(File.join(File.dirname(__FILE__), "..", "ssl", "server.key"))
cert_file = File.expand_path(File.join(File.dirname(__FILE__), "..", "ssl", "server.crt"))
pkey = OpenSSL::PKey::RSA.new(File.read(private_key_file))
cert = OpenSSL::X509::Certificate.new(File.read(cert_file))
pid_file = ENV["PID_FILE"]
s = WEBrick::HTTPServer.new(
:Port => (ENV['SSL_TEST_PORT'] || 8443),
:Logger => WEBrick::Log::new(nil, WEBrick::Log::ERROR),
:DocumentRoot => File.join(File.dirname(__FILE__)),
:ServerType => WEBrick::Daemon,
:SSLEnable => true,
:SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE,
:SSLCertificate => cert,
:SSLPrivateKey => pkey,
:SSLCertName => [ [ "CN",WEBrick::Utils::getservername ] ],
:StartCallback => proc { File.open(pid_file, "w") { |f| f.write $$.to_s }}
)
s.mount_proc("/") { |req,resp| resp.body = "hello world" }
trap("INT"){ s.shutdown }
s.start
| 34.310345 | 97 | 0.675377 |
21ae29e9f21b5492fcfadfba3a52e7117f160e8c | 182 | class <%= class_name %> < <%= parent_class_name.classify %>
<% attributes.select {|attr| attr.reference? }.each do |attribute| -%>
belongs_to :<%= attribute.name %>
<% end -%>
end
| 30.333333 | 70 | 0.642857 |
87903a1570da1e2cacbe055836ac0eb248313a73 | 3,564 | module PaypalHelper
TxApi = TransactionService::API::Api
module_function
# Check that we have an active provisioned :paypal payment gateway
# for the community AND that the community admin has fully
# configured the gateway.
def community_ready_for_payments?(community_id)
account_prepared_for_community?(community_id) &&
Maybe(TransactionService::API::Api.settings.get_active_by_gateway(community_id: community_id, payment_gateway: :paypal))
.map {|res| res[:success] ? res[:data] : nil}
.select {|set| set[:payment_gateway] == :paypal && set[:commission_from_seller] && set[:minimum_price_cents]}
.map {|_| true}
.or_else(false)
end
# Check that both the community is fully configured with an active
# :paypal payment gateway and that the given user has connected his
# paypal account.
def user_and_community_ready_for_payments?(person_id, community_id)
PaypalHelper.account_prepared_for_user?(person_id, community_id) &&
PaypalHelper.community_ready_for_payments?(community_id)
end
# Check that the user has connected his paypal account for the
# community
def account_prepared_for_user?(person_id, community_id)
payment_settings =
TransactionService::API::Api.settings.get(
community_id: community_id,
payment_gateway: :paypal,
payment_process: :preauthorize)
.maybe
account_prepared?(community_id: community_id, person_id: person_id, settings: payment_settings)
end
def account_prepared_for_community?(community_id)
account_prepared?(community_id: community_id)
end
# Private
def account_prepared?(community_id:, person_id: nil, settings: Maybe(nil))
acc_state = accounts_api.get(community_id: community_id, person_id: person_id).maybe()[:state].or_else(:not_connected)
commission_type = settings[:commission_type].or_else(nil)
acc_state == :verified || (acc_state == :connected && commission_type == :none)
end
private_class_method :account_prepared?
# Check that the currently active payment gateway (there can be only
# one active at any time) for the community is :paypal. This doesn't
# check that the gateway is fully configured. Use
# community_ready_for_payments? if that's what you need.
def paypal_active?(community_id)
settings = Maybe(TxApi.settings.get(community_id: community_id, payment_gateway: :paypal, payment_process: :preauthorize))
.select { |result| result[:success] }
.map { |result| result[:data] }
.or_else(nil)
return settings && settings[:active]
end
# Check if PayPal has been provisioned for a community.
#
# This is different from PayPal being active. Provisioned just means
# that admin can configure and activate PayPal.
def paypal_provisioned?(community_id)
settings = Maybe(TxApi.settings.get(
community_id: community_id,
payment_gateway: :paypal,
payment_process: :preauthorize))
.select { |result| result[:success] }
.map { |result| result[:data] }
.or_else(nil)
return !!settings
end
# Check if the user has open listings in the community but has not
# finished connecting his paypal account.
def open_listings_with_missing_payment_info?(user_id, community_id)
paypal_active?(community_id) &&
!user_and_community_ready_for_payments?(user_id, community_id) &&
PaymentHelper.open_listings_with_payment_process?(community_id, user_id)
end
def accounts_api
PaypalService::API::Api.accounts
end
end
| 37.515789 | 126 | 0.729517 |
1ccc6a67ec53460ab1adf5fa1ef346b847e635a3 | 305 | class AppDelegate
def application(application, didFinishLaunchingWithOptions:launchOptions)
controller = GameViewController.alloc.init
@window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
@window.rootViewController = controller
@window.makeKeyAndVisible
true
end
end
| 30.5 | 75 | 0.796721 |
ab032509182e2a656a230bd3afee254a79683dc1 | 2,872 | cask 'little-snitch-nightly' do
version '4.3,5260'
sha256 'ff2a894bc1f14fff02875aab3ce7d647c11863a19cbb26514692d800725158aa'
url "https://obdev.at/downloads/littlesnitch/nightly/LittleSnitch-#{version.before_comma}-nightly-(#{version.after_comma}).dmg"
appcast 'https://www.obdev.at/products/littlesnitch/releasenotes-nightly.html'
name 'Little Snitch Nightly Build'
homepage 'https://obdev.at/products/littlesnitch/download-nightly.html'
auto_updates true
conflicts_with cask: 'little-snitch'
depends_on macos: '>= :el_capitan'
container type: :naked
installer manual: "LittleSnitch-#{version.before_comma}-nightly-(#{version.after_comma}).dmg/Little Snitch Installer.app"
uninstall launchctl: [
'at.obdev.LittleSnitchUIAgent',
'at.obdev.LittleSnitchHelper',
'at.obdev.littlesnitchd',
]
zap trash: [
'/Library/Application Support/Objective Development/Little Snitch',
'/Library/Caches/at.obdev.LittleSnitchConfiguration',
'/Library/Little Snitch',
'/Library/Logs/LittleSnitchDaemon.log',
'~/Library/Application Support/Little Snitch',
'~/Library/Caches/at.obdev.LittleSnitchAgent',
'~/Library/Caches/at.obdev.LittleSnitchConfiguration',
'~/Library/Caches/at.obdev.LittleSnitchHelper',
'~/Library/Caches/at.obdev.LittleSnitchSoftwareUpdate',
'~/Library/Caches/com.apple.helpd/Generated/at.obdev.LittleSnitchConfiguration.help*',
'~/Library/Caches/com.apple.helpd/SDMHelpData/Other/English/HelpSDMIndexFile/at.obdev.LittleSnitchConfiguration.help*',
'~/Library/Logs/Little Snitch Agent.log',
'~/Library/Logs/Little Snitch Helper.log',
'~/Library/Logs/Little Snitch Installer.log',
'~/Library/Logs/Little Snitch Network Monitor.log',
'~/Library/Preferences/at.obdev.LittleSnitchAgent.plist',
'~/Library/Preferences/at.obdev.LittleSnitchConfiguration.plist',
'~/Library/Preferences/at.obdev.LittleSnitchInstaller.plist',
'~/Library/Preferences/at.obdev.LittleSnitchNetworkMonitor.plist',
'~/Library/Preferences/at.obdev.LittleSnitchSoftwareUpdate.plist',
'~/Library/Saved Application State/at.obdev.LittleSnitchInstaller.savedState',
'~/Library/WebKit/at.obdev.LittleSnitchConfiguration',
# These kext's should not be uninstalled by Cask
'/Library/Extensions/LittleSnitch.kext',
'/Library/StagedExtensions/Library/Extensions/LittleSnitch.kext',
],
rmdir: '/Library/Application Support/Objective Development'
caveats do
kext
reboot
end
end
| 50.385965 | 134 | 0.658078 |
5d8ab75aa8aee6faefe27724f21981211fc733dd | 8,083 | # frozen_string_literal: true
require 'spec_helper'
describe RuboCop::AST::IfNode do
let(:if_node) { parse_source(source).ast }
describe '.new' do
context 'with a regular if statement' do
let(:source) { 'if foo?; :bar; end' }
it { expect(if_node).to be_a(described_class) }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { expect(if_node).to be_a(described_class) }
end
context 'with a modifier statement' do
let(:source) { ':foo if bar?' }
it { expect(if_node).to be_a(described_class) }
end
end
describe '#keyword' do
context 'with an if statement' do
let(:source) { 'if foo?; :bar; end' }
it { expect(if_node.keyword).to eq('if') }
end
context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { expect(if_node.keyword).to eq('unless') }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { expect(if_node.keyword).to eq('') }
end
end
describe '#inverse_keyword?' do
context 'with an if statement' do
let(:source) { 'if foo?; :bar; end' }
it { expect(if_node.inverse_keyword).to eq('unless') }
end
context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { expect(if_node.inverse_keyword).to eq('if') }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { expect(if_node.inverse_keyword).to eq('') }
end
end
describe '#if?' do
context 'with an if statement' do
let(:source) { 'if foo?; :bar; end' }
it { expect(if_node.if?).to be_truthy }
end
context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { expect(if_node.if?).to be_falsey }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { expect(if_node.if?).to be_falsey }
end
end
describe '#unless?' do
context 'with an if statement' do
let(:source) { 'if foo?; :bar; end' }
it { expect(if_node.unless?).to be_falsey }
end
context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { expect(if_node.unless?).to be_truthy }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { expect(if_node.unless?).to be_falsey }
end
end
describe '#ternary?' do
context 'with an if statement' do
let(:source) { 'if foo?; :bar; end' }
it { expect(if_node.ternary?).to be_falsey }
end
context 'with an unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { expect(if_node.ternary?).to be_falsey }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { expect(if_node.ternary?).to be_truthy }
end
end
describe '#elsif?' do
context 'with an elsif statement' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'end'].join("\n")
end
let(:elsif_node) { if_node.else_branch }
it { expect(elsif_node.elsif?).to be_truthy }
end
context 'with an if statement comtaining an elsif' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'end'].join("\n")
end
it { expect(if_node.elsif?).to be_falsey }
end
context 'without an elsif statement' do
let(:source) do
['if foo?',
' 1',
'end'].join("\n")
end
it { expect(if_node.elsif?).to be_falsey }
end
end
describe '#else?' do
context 'with an elsif statement' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'end'].join("\n")
end
# Note: This is a legacy behaviour.
it { expect(if_node.else?).to be_truthy }
end
context 'without an else statement' do
let(:source) do
['if foo?',
' 1',
'else',
' 2',
'end'].join("\n")
end
it { expect(if_node.elsif?).to be_falsey }
end
end
describe '#modifier_form?' do
context 'with a non-modifier if statement' do
let(:source) { 'if foo?; :bar; end' }
it { expect(if_node.modifier_form?).to be_falsey }
end
context 'with a non-modifier unless statement' do
let(:source) { 'unless foo?; :bar; end' }
it { expect(if_node.modifier_form?).to be_falsey }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :bar : :baz' }
it { expect(if_node.modifier_form?).to be_falsey }
end
context 'with a modifier if statement' do
let(:source) { ':bar if foo?' }
it { expect(if_node.modifier_form?).to be_truthy }
end
context 'with a modifier unless statement' do
let(:source) { ':bar unless foo?' }
it { expect(if_node.modifier_form?).to be_truthy }
end
end
describe '#nested_conditional?' do
context 'with no nested conditionals' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'else',
' 3',
'end'].join("\n")
end
it { expect(if_node.nested_conditional?).to be_falsey }
end
context 'with nested conditionals in if clause' do
let(:source) do
['if foo?',
' if baz; 4; end',
'elsif bar?',
' 2',
'else',
' 3',
'end'].join("\n")
end
it { expect(if_node.nested_conditional?).to be_truthy }
end
context 'with nested conditionals in elsif clause' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' if baz; 4; end',
'else',
' 3',
'end'].join("\n")
end
it { expect(if_node.nested_conditional?).to be_truthy }
end
context 'with nested conditionals in else clause' do
let(:source) do
['if foo?',
' 1',
'elsif bar?',
' 2',
'else',
' if baz; 4; end',
'end'].join("\n")
end
it { expect(if_node.nested_conditional?).to be_truthy }
end
context 'with nested ternary operators' do
context 'when nested in the truthy branch' do
let(:source) { 'foo? ? bar? ? 1 : 2 : 3' }
it { expect(if_node.nested_conditional?).to be_truthy }
end
context 'when nested in the falsey branch' do
let(:source) { 'foo? ? 3 : bar? ? 1 : 2' }
it { expect(if_node.nested_conditional?).to be_truthy }
end
end
end
describe '#if_branch' do
context 'with an if statement' do
let(:source) do
['if foo?',
' :foo',
'else',
' 42',
'end'].join("\n")
end
it { expect(if_node.if_branch).to be_sym_type }
end
context 'with an unless statement' do
let(:source) do
['unless foo?',
' :foo',
'else',
' 42',
'end'].join("\n")
end
it { expect(if_node.if_branch).to be_sym_type }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :foo : 42' }
it { expect(if_node.if_branch).to be_sym_type }
end
end
describe '#else_branch' do
context 'with an if statement' do
let(:source) do
['if foo?',
' :foo',
'else',
' 42',
'end'].join("\n")
end
it { expect(if_node.else_branch).to be_int_type }
end
context 'with an unless statement' do
let(:source) do
['unless foo?',
' :foo',
'else',
' 42',
'end'].join("\n")
end
it { expect(if_node.else_branch).to be_int_type }
end
context 'with a ternary operator' do
let(:source) { 'foo? ? :foo : 42' }
it { expect(if_node.else_branch).to be_int_type }
end
end
end
| 22.390582 | 63 | 0.533342 |
3857c3192453b766e22218ae97575d214658b603 | 1,730 | # FilesController
class FilesController < ApplicationController
# We manually add the authorize the calling of actions using the authorize_action method below...
def create
if params.has_key?(:Filedata)
success, message = process_files
else
success = false
message = "You must specify a file to upload"
end
respond_to do |format|
if success
notice = { notice: message }
format.html { redirect_to :back, notice }
else
notice = { :error => message }
format.html { redirect_to :back, notice }
end
end
end
def destroy
container_id = params[:container_id]
index = params[:index]
container = ActiveFedora::Base.find(container_id, cast: true)
# Manually call authorize_action
authorize_action(container)
success, deleted_asset_id, message = container.delete_by_content_metadata_resource_at(index.to_i)
respond_to do |format|
if success
notice = { notice: message }
format.html { redirect_to :back, notice }
else
notice = { error: message }
format.html { redirect_to :back, notice }
end
end
end
private
def process_files
container_id = params[:container_id]
container = ActiveFedora::Base.find(container_id, cast: true)
# Manually call authorize_action
authorize_action(container)
success, file_assets, message = container.add_file_content(params[:Filedata])
return success, message
end
# Authorize action will authorize the action based upon the containers object rights for an update (edit)
def authorize_action(container_object)
authorize! :update, container_object
end
end | 26.615385 | 107 | 0.675723 |
1c0f99dac701c9fbeafb3de0f4d8b6c481d5a36e | 1,201 | require 'rails_helper'
RSpec.describe Organisation, type: :model do
let(:organisation) { build(:organisation) }
let(:program_service_accomplishment) { build(:program_service_accomplishment)}
let(:revenue) { build(:revenue)}
describe "attributes" do
it { should have_db_column(:name) }
it { should have_db_column(:mission) }
it { should have_db_column(:address) }
it { should have_db_column(:year_formed) }
it { should have_db_column(:number_of_employees) }
it { should have_db_column(:domain) }
it { should have_db_column(:ein) }
it { should have_db_column(:masterfile_id) }
end
describe "associations" do
it { should have_many(:executives) }
it { should have_many(:balances) }
it { should have_many(:revenues) }
it { should have_many(:expenses) }
it { should have_many(:program_service_accomplishments) }
it { should belong_to(:masterfile) }
end
describe "instance methods" do
it "returns program service accomplishments in an array" do
p_s_a = organisation.render_program_service_accomplishments
p_s_a.each do |psa|
expect(psa.class).to eq(ProgramServiceAccomplishment)
end
end
end
end
| 31.605263 | 80 | 0.706911 |
bf187c8407884e3f817fea8d9f69e2f8b3af3129 | 7,412 | describe EmbeddedAnsibleWorker do
subject { FactoryGirl.create(:embedded_ansible_worker) }
context "ObjectManagement concern" do
let(:provider) { FactoryGirl.create(:provider_embedded_ansible) }
let(:api_connection) { double("AnsibleAPIConnection", :api => tower_api) }
let(:tower_api) do
methods = {
:organizations => org_collection,
:credentials => cred_collection,
:inventories => inv_collection,
:hosts => host_collection,
:job_templates => job_templ_collection,
:projects => proj_collection
}
double("TowerAPI", methods)
end
let(:org_collection) { double("AnsibleOrgCollection", :all => [org_resource]) }
let(:cred_collection) { double("AnsibleCredCollection", :all => [cred_resource]) }
let(:inv_collection) { double("AnsibleInvCollection", :all => [inv_resource]) }
let(:host_collection) { double("AnsibleHostCollection", :all => [host_resource]) }
let(:job_templ_collection) { double("AnsibleJobTemplCollection", :all => [job_templ_resource]) }
let(:proj_collection) { double("AnsibleProjCollection", :all => [proj_resource]) }
let(:org_resource) { double("AnsibleOrgResource", :id => 12) }
let(:cred_resource) { double("AnsibleCredResource", :id => 13) }
let(:inv_resource) { double("AnsibleInvResource", :id => 14) }
let(:host_resource) { double("AnsibleHostResource", :id => 15) }
let(:job_templ_resource) { double("AnsibleJobTemplResource", :id => 16) }
let(:proj_resource) { double("AnsibleProjResource", :id => 17) }
describe "#ensure_initial_objects" do
it "creates the expected objects" do
expect(org_collection).to receive(:create!).and_return(org_resource)
expect(cred_collection).to receive(:create!).and_return(cred_resource)
expect(inv_collection).to receive(:create!).and_return(inv_resource)
expect(host_collection).to receive(:create!).and_return(host_resource)
subject.ensure_initial_objects(provider, api_connection)
end
end
describe "#remove_demo_data" do
it "removes the existing data" do
expect(org_resource).to receive(:destroy!)
expect(cred_resource).to receive(:destroy!)
expect(inv_resource).to receive(:destroy!)
expect(job_templ_resource).to receive(:destroy!)
expect(proj_resource).to receive(:destroy!)
subject.remove_demo_data(api_connection)
end
end
describe "#ensure_organization" do
it "sets the provider default organization" do
expect(org_collection).to receive(:create!).with(
:name => "ManageIQ",
:description => "ManageIQ Default Organization"
).and_return(org_resource)
subject.ensure_organization(provider, api_connection)
expect(provider.default_organization).to eq(12)
end
it "doesn't recreate the organization if one is already set" do
provider.default_organization = 1
expect(org_collection).not_to receive(:create!)
subject.ensure_organization(provider, api_connection)
end
end
describe "#ensure_credential" do
it "sets the provider default credential" do
provider.default_organization = 123
expect(cred_collection).to receive(:create!).with(
:name => "ManageIQ Default Credential",
:kind => "ssh",
:organization => 123
).and_return(cred_resource)
subject.ensure_credential(provider, api_connection)
expect(provider.default_credential).to eq(13)
end
it "doesn't recreate the credential if one is already set" do
provider.default_credential = 2
expect(cred_collection).not_to receive(:create!)
subject.ensure_credential(provider, api_connection)
end
end
describe "#ensure_inventory" do
it "sets the provider default inventory" do
provider.default_organization = 123
expect(inv_collection).to receive(:create!).with(
:name => "ManageIQ Default Inventory",
:organization => 123
).and_return(inv_resource)
subject.ensure_inventory(provider, api_connection)
expect(provider.default_inventory).to eq(14)
end
it "doesn't recreate the inventory if one is already set" do
provider.default_inventory = 3
expect(inv_collection).not_to receive(:create!)
subject.ensure_inventory(provider, api_connection)
end
end
describe "#ensure_host" do
it "sets the provider default host" do
provider.default_inventory = 234
expect(host_collection).to receive(:create!).with(
:name => "localhost",
:inventory => 234,
:variables => "---\nansible_connection: local\n"
).and_return(host_resource)
subject.ensure_host(provider, api_connection)
expect(provider.default_host).to eq(15)
end
it "doesn't recreate the host if one is already set" do
provider.default_host = 1
expect(host_collection).not_to receive(:create!)
subject.ensure_host(provider, api_connection)
end
end
describe "#start_monitor_thread" do
it "sets worker class and id in thread object" do
allow(Thread).to receive(:new).and_return({})
allow(described_class::Runner).to receive(:start_worker)
thread = subject.start_monitor_thread
expect(thread[:worker_class]).to eq subject.class.name
expect(thread[:worker_id]).to eq subject.id
end
end
describe "#find_worker_thread_object" do
it "returns the the thread matching the class and id of the worker" do
worker1 = {:worker_id => subject.id + 1, :worker_class => "SomeOtherWorker"}
worker2 = {:worker_id => subject.id, :worker_class => subject.class.name}
allow(Thread).to receive(:list).and_return([worker1, worker2])
expect(subject.find_worker_thread_object).to eq(worker2)
end
it "returns nil if nothing matches" do
worker1 = {:worker_id => subject.id + 1, :worker_class => subject.class.name}
worker2 = {:worker_id => subject.id + 2, :worker_class => subject.class.name}
allow(Thread).to receive(:list).and_return([worker1, worker2])
expect(subject.find_worker_thread_object).to be_nil
end
end
describe "#kill" do
it "exits the monitoring thread and destroys the worker row" do
thread_double = double
expect(thread_double).to receive(:exit)
allow(subject).to receive(:find_worker_thread_object).and_return(thread_double)
subject.kill
expect { subject.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
it "destroys the worker row but refuses to kill the main thread" do
allow(subject).to receive(:find_worker_thread_object).and_return(Thread.main)
subject.kill
expect { subject.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
it "destroys the worker row if the monitor thread is not found" do
allow(subject).to receive(:find_worker_thread_object).and_return(nil)
subject.kill
expect { subject.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
| 39.636364 | 100 | 0.66109 |
d57e5591f1e6f645a94830c53f05959da7fe98d7 | 281 | # frozen_string_literal: true
module Faker
class Pokemon < Base
class << self
def name
fetch('pokemon.names')
end
def location
fetch('pokemon.locations')
end
def move
fetch('pokemon.moves')
end
end
end
end
| 14.05 | 34 | 0.565836 |
117344847cff213603c52906ae359bceac1fe5f1 | 4,372 | # frozen_string_literal: true
module ShipEngine
module Domain
class Addresses
module AddressValidation
class Response
attr_reader :status, :original_address, :matched_address, :messages
# type ["unverified" | "verified" | "warning" | "error"] status
# @param [NormalizedAddress] original_address
# @param [NormalizedAddress?] matched_address
# @param [Array<Response>] messages
def initialize(status:, original_address:, matched_address:, messages:)
@status = status
@original_address = original_address
@matched_address = matched_address
@messages = messages
end
end
class Request
attr_reader :address_line1, :address_line2, :address_line3, :name, :company_name, :phone, :city_locality, :state_province, :postal_code,
:country_code, :address_residential_indicator
# @param [String] address_line1 - e.g. ["123 FAKE ST."]
# @param [String?] address_line2 - e.g. ["123 FAKE ST."]
# @param [String?] address_line3 - e.g. ["123 FAKE ST."]
# @param [String] country_code - e.g. "US". @see https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes
# @param [String] postal_code - e.g "78751"
# @param [String?] name - e.g. "John Smith"
# @param [String?] company_name - e.g. "ShipEngine"
# @param [String?] phone - e.g. 5551234567
# @param [String?] city_locality - e.g. "AUSTIN"
# @param [String?] state_province - e.g. "TX"
# @param [String?] address_residential_indicator
def initialize(address_line1:, address_line2:, address_line3:, name:, company_name:, phone:, city_locality:, state_province:, postal_code:,
country_code:, address_residential_indicator:)
@name = name
@company_name = company_name
@address_line1 = address_line1
@address_line2 = address_line2
@address_line3 = address_line3
@phone = phone
@city_locality = city_locality
@state_province = state_province
@postal_code = postal_code
@country_code = country_code
@address_residential_indicator = address_residential_indicator
end
end
class Address
attr_reader :address_line1, :address_line2, :address_line3, :name, :company_name, :phone, :city_locality, :state_province, :postal_code,
:country_code, :address_residential_indicator
# @param [String] address_line1 - e.g. ["123 FAKE ST."]
# @param [String?] address_line2 - e.g. ["123 FAKE ST."]
# @param [String?] address_line3 - e.g. ["123 FAKE ST."]
# @param [String] country_code - e.g. "US". @see https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes
# @param [String] postal_code - e.g "78751"
# @param [String?] name - e.g. "John Smith"
# @param [String?] company_name - e.g. "ShipEngine"
# @param [String?] phone - e.g. 5551234567
# @param [String?] city_locality - e.g. "AUSTIN"
# @param [String?] state_province - e.g. "TX"
# @param [String?] address_residential_indicator
def initialize(address_line1:, address_line2:, address_line3:, name:, company_name:, phone:, city_locality:, state_province:, postal_code:,
country_code:, address_residential_indicator:)
@name = name
@company_name = company_name
@address_line1 = address_line1
@address_line2 = address_line2
@address_line3 = address_line3
@phone = phone
@city_locality = city_locality
@state_province = state_province
@postal_code = postal_code
@country_code = country_code
@address_residential_indicator = address_residential_indicator
end
end
class Message
attr_reader :type, :code, :message
# @param type [:info" | :warning | :error"]
# @param code [String] = e.g. "suite_missing"
def initialize(type:, code:, message:)
@type = type
@code = code
@message = message
end
end
end
end
end
end
| 43.72 | 149 | 0.602242 |
b9b8df187ef4ee92a6c95b9b75b4cdfb758d988c | 1,811 | #
# Copyright (c) 2017 Red Hat, 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.
#
#
# This class is responsible for parsing the inventory for full refreshes.
#
class ManageIQ::Providers::Kubevirt::Inventory::Parser::FullRefresh < ManageIQ::Providers::Kubevirt::Inventory::Parser
def parse
# Get the objects from the collector:
nodes = collector.nodes
vms = collector.vms
vm_instances = collector.vm_instances
templates = collector.templates
# Create the collections:
@cluster_collection = persister.cluster_collection
@host_collection = persister.host_collection
@host_storage_collection = persister.host_storage_collection
@hw_collection = persister.hw_collection
@network_collection = persister.network_collection
@os_collection = persister.os_collection
@storage_collection = persister.storage_collection
@template_collection = persister.template_collection
@vm_collection = persister.vm_collection
@vm_os_collection = persister.vm_os_collection
@disk_collection = persister.disk_collection
# Add the built-in objects:
add_builtin_clusters
add_builtin_storages
# Process the real objects:
process_nodes(nodes)
process_vms(vms)
process_vm_instances(vm_instances)
process_templates(templates)
end
end
| 34.826923 | 118 | 0.764219 |
ed3b551a1ccbf7b10bcfd2dbd1ed365957adc520 | 289 | # frozen_string_literal: true
require 'pathname'
module PathHelper
module_function
def project_root_path
Pathname.new(File.expand_path('../..', __dir__))
end
def tmp_path
project_root_path.join('tmp')
end
def dest_path
project_root_path.join('dest')
end
end
| 14.45 | 52 | 0.719723 |
26dd51afa960890fb135590846c899054caaa076 | 910 | # frozen_string_literal: true
require File.dirname(__FILE__) + '/spec_helper'
RSpec.describe "YARD::Handlers::Ruby::#{LEGACY_PARSER ? "Legacy::" : ""}PrivateConstantHandler" do
before(:all) { parse_file :private_constant_handler_001, __FILE__ }
it "handles private_constant statement" do
expect(Registry.at('A::Foo').visibility).to eq :private
expect(Registry.at('A::B').visibility).to eq :private
expect(Registry.at('A::C').visibility).to eq :private
end
it "makes all other constants public" do
expect(Registry.at('A::D').visibility).to eq :public
end
it "fails if parameter is not String, Symbol or Constant" do
undoc_error 'class Foo; private_constant x; end'
undoc_error 'class Foo; X = 1; private_constant X.new("hi"); end'
end unless LEGACY_PARSER
it "fails if constant can't be recognized" do
undoc_error 'class Foo2; private_constant :X end'
end
end
| 35 | 98 | 0.71978 |
18a1434dc2c6b46105b16775fedfa269687d480d | 616 | module Goosi
# User device and its capabilities
class Device
# Read device capabilities
def initialize(device)
@capabilities = []
return if device[:capabilities].nil?
device[:capabilities].each do |c|
@capabilities << c[:name]
end
end
# Does that device supports audio output?
#
# @return [Boolean]
def speakers?
@capabilities.include? 'actions.capability.AUDIO_OUTPUT'
end
# Does that device have screen?
#
# @return [Boolean]
def screen?
@capabilities.include? 'actions.capability.SCREEN_OUTPUT'
end
end
end
| 20.533333 | 63 | 0.636364 |
62aa0e34406c0b016e162f54cbb8ff48d84d352a | 1,272 | class Project < ActiveRecord::Base
include ProjectValidations
include ProjectAssociations
include ProjectCallbacks
acts_as_paranoid
serialize :builder_options, JSON
serialize :execution_variables, JSON
delegate :requires_build?, :target, to: :script, allow_nil: true
after_initialize :set_default_execution_variables
def set_default_execution_variables
self.execution_variables = HashWithIndifferentAccess.new unless self.execution_variables.present?
execution_variables_required.each do |required_execution_variable|
self.execution_variables[required_execution_variable.name.to_s] = required_execution_variable.default_value unless self.execution_variables[required_execution_variable.name.to_s].present?
end
end
def execution_variables_required
if @execution_variables_required.nil?
@execution_variables_required = []
@execution_variables_required = @execution_variables_required | script.execution_variables if script.present?
@execution_variables_required = @execution_variables_required | builder.execution_variables_required if builder.present?
end
@execution_variables_required
end
def builder
@builder ||= Builders::Registry.find_by_builder_name(self.builder_name)
end
end
| 36.342857 | 193 | 0.813679 |
4ab0cf728bf0610d2c7b3ca2100538913c00f3ee | 201 | class CreateGenericPractises < ActiveRecord::Migration[6.1]
def change
create_table :generic_practises do |t|
t.string :name
t.integer :position
t.timestamps
end
end
end
| 18.272727 | 59 | 0.686567 |
bbbeee27d0e0cb08b7bf81eb7dffea0a5d2d6e37 | 30 | module AdminpromoteHelper
end
| 10 | 25 | 0.9 |
ff7ecc39b77814aa3bdfb54ba2ffcf1aadf1826c | 559 | # frozen_string_literal: true
Gem::Specification.new do |spec|
spec.name = "obsidian-theme"
spec.version = "0.1.0"
spec.authors = ["Matt Coley"]
spec.email = ["[email protected]"]
spec.summary = %q{A simplistic dark theme}
spec.homepage = "https://github.com/Col-E/Jekyll-Obsidian"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r!^(assets|_layouts|_includes|_sass|LICENSE|README|_config\.yml)!i) }
spec.add_runtime_dependency "jekyll", ">= 4"
end
| 39.928571 | 145 | 0.618962 |
e98bcb89eece483bd3e063efee8cf8f378960fd5 | 2,973 | ##
# $Id$
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Remote::HttpServer::HTML
def initialize(info = {})
super(update_info(info,
'Name' => 'Facebook Photo Uploader 4 ActiveX Control Buffer Overflow',
'Description' => %q{
This module exploits a stack buffer overflow in Facebook Photo Uploader 4.
By sending an overly long string to the "ExtractIptc()" property located
in the ImageUploader4.ocx (4.5.57.0) Control, an attacker may be able to execute
arbitrary code.
},
'License' => MSF_LICENSE,
'Author' => [ 'MC' ],
'Version' => '$Revision$',
'References' =>
[
[ 'CVE', '2008-5711' ],
[ 'OSVDB', '41073' ],
[ 'BID', '27534' ],
[ 'EDB', '5049' ]
],
'DefaultOptions' =>
{
'EXITFUNC' => 'process',
},
'Payload' =>
{
'Space' => 800,
'BadChars' => "\x00\x09\x0a\x0d'\\",
'StackAdjustment' => -3500,
},
'Platform' => 'win',
'Targets' =>
[
[ 'IE 6 SP0-SP2 / Windows XP SP2 Pro English', { 'Ret' => 0x74c9de3e } ], # 02/07/08
], # ./msfpescan -i /tmp/oleacc.dll | grep SEHandler
'DisclosureDate' => 'Jan 31 2008',
'DefaultTarget' => 0))
end
def autofilter
false
end
def check_dependencies
use_zlib
end
def on_request_uri(cli, request)
# Re-generate the payload
return if ((p = regenerate_payload(cli)) == nil)
# Randomize some things
vname = rand_text_alpha(rand(100) + 1)
strname = rand_text_alpha(rand(100) + 1)
rand1 = rand_text_alpha(rand(100) + 1)
rand2 = rand_text_alpha(rand(100) + 1)
rand3 = rand_text_alpha(rand(100) + 1)
rand4 = rand_text_alpha(rand(100) + 1)
# Set the exploit buffer
filler = Rex::Text.to_unescape(rand_text_alpha(2))
jmp = Rex::Text.to_unescape([0x969606eb].pack('V'))
ret = Rex::Text.to_unescape([target.ret].pack('V'))
sc = Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(target.arch))
# Build out the message
content = %Q|<html>
<object classid='clsid:5C6698D9-7BE4-4122-8EC5-291D84DBD4A0' id='#{vname}'></object>
<script language='javascript'>
#{rand1} = unescape('#{filler}');
while (#{rand1}.length <= 261) #{rand1} = #{rand1} + unescape('#{filler}');
#{rand2} = unescape('#{jmp}');
#{rand3} = unescape('#{ret}');
#{rand4} = unescape('#{sc}');
#{strname} = #{rand1} + #{rand2} + #{rand3} + #{rand4};
#{vname}.ExtractIptc = #{strname};
</script>
</html>
|
print_status("Sending #{self.name}")
# Transmit the response to the client
send_response_html(cli, content)
# Handle the payload
handler(cli)
end
end
| 27.527778 | 93 | 0.607804 |
91103a2ad0ea61462ec2ae6e2d62ec5b4e0ece4d | 584 | FROM centos:7
MAINTAINER "Aslak Knutsen <[email protected]>"
ENV LANG=en_US.utf8
# Some packages might seem weird but they are required by the RVM installer.
RUN yum --enablerepo=centosplus install -y \
findutils \
git \
golang \
make \
procps-ng \
tar \
wget \
which \
&& yum clean all
# Get dep for Go package management
RUN mkdir -p /tmp/go/bin
ENV GOPATH /tmp/go
RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh && mv /tmp/go/bin/dep /usr/bin
RUN chmod -R a+rwx ${GOPATH}
ENTRYPOINT ["/bin/bash"]
| 23.36 | 107 | 0.660959 |
21779d50e52431c2963b751abd793d263a65d5b6 | 1,905 | class HowardHinnantDate < Formula
desc "C++ library for date and time operations based on <chrono>"
homepage "https://github.com/HowardHinnant/date"
url "https://github.com/HowardHinnant/date/archive/v3.0.1.tar.gz"
sha256 "7a390f200f0ccd207e8cff6757e04817c1a0aec3e327b006b7eb451c57ee3538"
license "MIT"
bottle do
sha256 cellar: :any, arm64_monterey: "52811eb710a07d879d153a65bc6c771a8ff801f990a6bd2f968d1238c6000b03"
sha256 cellar: :any, arm64_big_sur: "deff47e2027f805ef5cd430d0700470cf8bada0cde442e8674ae6a832e3b9888"
sha256 cellar: :any, monterey: "0098680dad7ff5cb5854d04ab0aff279641892d1c8c3079658bfe2762bb1b6f9"
sha256 cellar: :any, big_sur: "b8fc90e684f2d3b711fcb405c082f8ad637eac8f6c5816b746284c911950eb5a"
sha256 cellar: :any, catalina: "bebf754666baa69673a77fb5eeb3c0ebe9931b7aa2d3991a3f6fa235a439d11b"
sha256 cellar: :any, mojave: "d140b4b590c5ef8c25e80abaa8466dbcb6f10a95ca0dec551de7fb0e213171b4"
sha256 cellar: :any_skip_relocation, x86_64_linux: "2361559d178154d8e6f69b1da915838ab17271a61d3ff808db1ed2ca8ce7091f"
end
depends_on "cmake" => :build
def install
system "cmake", ".", *std_cmake_args,
"-DENABLE_DATE_TESTING=OFF",
"-DUSE_SYSTEM_TZ_DB=ON",
"-DBUILD_SHARED_LIBS=ON",
"-DBUILD_TZ_LIB=ON"
system "make", "install"
end
test do
(testpath/"test.cpp").write <<~EOS
#include "date/tz.h"
#include <iostream>
int main() {
auto t = date::make_zoned(date::current_zone(), std::chrono::system_clock::now());
std::cout << t << std::endl;
}
EOS
system ENV.cxx, "test.cpp", "-std=c++1y", "-L#{lib}", "-ldate-tz", "-o", "test"
system "./test"
end
end
| 44.302326 | 123 | 0.654068 |
f878ea1f02045b401592a437833b958111f47820 | 4,185 | class ObservationsController < ApplicationController
before_action :authenticate_user!
before_action :set_grow, only: [:index, :new, :show, :edit, :create, :update, :destroy]
before_action :set_subject, only: [:index, :new, :show, :edit, :create, :update, :destroy]
before_action :set_observation, only: [:show, :edit, :update, :destroy]
# GET /observations
# GET /observations.json
def index
@observations = Observation.all
end
# GET /observations/1
# GET /observations/1.json
def show
commontator_thread_show @observation
end
# GET /observations/new
def new
add_breadcrumb "New observation"
@observation = Observation.new
if current_user.observations.last
current_user.observations.last.resource_datas.each do |rd|
@observation.resource_datas.build(
resource_id: rd.resource_id,
observation_id: rd.observation_id,
value: rd.value,
unit: rd.unit,
category_id: rd.resource.category_id
)
end
end
end
# GET /observations/1/edit
def edit
end
# POST /observations
# POST /observations.json
def create
@observation = Observation.new(observation_params)
respond_to do |format|
if @observation.save
message = "New observation has been created by <b>#{current_user.username}</b>"
Event.create!(event_type: :action, message: message, eventable: @observation, user_id: current_user.id)
if @subject
format.html { redirect_to [@grow, @subject], notice: 'Observation was successfully created.' }
else
format.html { redirect_to @grow, notice: 'Observation was successfully created.' }
end
format.json { render :show, status: :created, location: @observation }
else
format.html { render :new }
format.json { render json: @observation.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /observations/1
# PATCH/PUT /observations/1.json
def update
respond_to do |format|
if @observation.update(observation_params)
format.html { redirect_to [@grow, @subject], notice: 'Observation was successfully updated.' }
format.json { render :show, status: :ok, location: @observation }
else
format.html { render :edit }
format.json { render json: @observation.errors, status: :unprocessable_entity }
end
end
end
# DELETE /observations/1
# DELETE /observations/1.json
def destroy
@observation.destroy
respond_to do |format|
format.html { redirect_to @grow, notice: 'Observation was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_grow
if params[:grow_id].present?
@grow = Grow.find(params[:grow_id])
add_breadcrumb "Grow ##{@grow.id}", @grow
elsif params[:observation] and observation_params[:grow_id].present?
@grow = Grow.find(observation_params[:grow_id])
add_breadcrumb "Grow ##{@grow.id}", @grow
end
end
def set_subject
if params[:subject_id].present?
@subject = Subject.find(params[:subject_id])
add_breadcrumb "#{@subject.name}", [@grow, @subject]
end
end
# Use callbacks to share common setup or constraints between actions.
def set_observation
@observation = Observation.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def observation_params
params.require(:observation).permit(
:user_id,
:grow_id,
:room_id,
:subject_id,
:body,
:water,
:nutrients,
subject_ids: [],
pictures: [],
resource_datas_attributes: [
:id,
:subject_id,
:observation_id,
:resource_id,
:value,
:unit,
:_destroy
],
issues_attributes: [
:id,
:subject_id,
:observation_id,
:resource_id,
:issue_type,
:issue_status,
:severity,
:_destroy
])
end
end
| 27.532895 | 111 | 0.626284 |
39d1e0e00c38fee59b6fe45c8f8baa6baab4b893 | 301 | class CreatePermissions < ActiveRecord::Migration[6.1]
def change
create_table :permissions do |t|
t.string :name, null: false
t.string :description, null: false
t.string :code, null: false
t.timestamps
end
add_index :permissions, :code, unique: true
end
end
| 21.5 | 54 | 0.667774 |
ed5b6d044fe75ca855dd4dab55b3abf20f2cd1f6 | 874 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'sortable_columns/version'
Gem::Specification.new do |spec|
spec.name = "sortable_columns"
spec.version = SortableColumns::VERSION
spec.authors = ["Daniel LaBare"]
spec.email = ["[email protected]"]
spec.description = %q{Simple sortable columns for your Rails app}
spec.summary = %q{Sort a simple dataset by column headers}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
end
| 36.416667 | 74 | 0.657895 |
26154dab7de0a1b11d7397805dad43fd2b808253 | 123 | class RemovePublicFromGroups < ActiveRecord::Migration
def change
remove_column :groups, :public, :boolean
end
end
| 20.5 | 54 | 0.772358 |
0109c8a01bb6882ad041a03cf15d3ca0972d25ad | 326 | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :authenticate_person!
def user_for_paper_trail
current_person.nil? ? "" : current_person.id
end
end
| 27.166667 | 56 | 0.773006 |
280cb05d58069c1c439e64800b64753e8bf7a144 | 1,323 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core/handler/reverse_https'
require 'msf/base/sessions/meterpreter_options'
require 'msf/base/sessions/mettle_config'
require 'msf/base/sessions/meterpreter_armle_linux'
module MetasploitModule
CachedSize = 1022588
include Msf::Payload::Single
include Msf::Sessions::MeterpreterOptions
include Msf::Sessions::MettleConfig
def initialize(info = {})
super(
update_info(
info,
'Name' => 'Linux Meterpreter, Reverse HTTPS Inline',
'Description' => 'Run the Meterpreter / Mettle server payload (stageless)',
'Author' => [
'Adam Cammack <adam_cammack[at]rapid7.com>',
'Brent Cook <brent_cook[at]rapid7.com>',
'timwr'
],
'Platform' => 'linux',
'Arch' => ARCH_ARMLE,
'License' => MSF_LICENSE,
'Handler' => Msf::Handler::ReverseHttps,
'Session' => Msf::Sessions::Meterpreter_armle_Linux
)
)
end
def generate
opts = {
scheme: 'https',
stageless: true
}
MetasploitPayloads::Mettle.new('armv5l-linux-musleabi', generate_config(opts)).to_binary :exec
end
end
| 28.148936 | 98 | 0.631897 |
edc5ec74d1c7a09db468deae18413bb00a6b0af3 | 441 | class MessageMailer < ActionMailer::Base
default from: '[email protected]'
def notify(member, message)
@message = message
@member = member
mail(mail_args(member, "You have a new message")) do |format|
format.html
end
end
helper do
def full_url_for path
"#{@host}#{path}"
end
end
private
def mail_args(member, subject)
{ :to => member.email,
:subject => subject }
end
end
| 17.64 | 65 | 0.630385 |
f7f32473e1343f9f87f66ac3c167e43070bc8946 | 390 | class Api::V1::AuthenticationController < ApiController
skip_before_action :authenticate_token!
def create
user = User.find_by(email: params[:user][:email])
if user.valid_password? params[:user][:password]
render json: {token: JsonWebToken.encode(sub: user.id)}
else
render json: {errors: ["Invalid email or passowrd"]}, status: :unauthorized
end
end
end
| 30 | 81 | 0.707692 |
1cfdaf0ed470633e9ab90834f3a34685ea029370 | 16,208 | =begin
This file is part of Viewpoint; the Ruby library for Microsoft Exchange Web Services.
Copyright © 2011 Dan Wanek <[email protected]>
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.
=end
module Viewpoint
module EWS
module ItemFieldUriMap
FIELD_URIS= {
:folder_id => {:text => 'folder:FolderId', :writable => true},
:total_count => {:text => 'folder:TotalCount', :writable => true},
:child_folder_count => {:text => 'folder:ChildFolderCount', :writable => true},
:folder_class => {:text => 'folder:FolderClass', :writable => true},
:search_parameters => {:text => 'folder:SearchParameters', :writable => true},
:managed_folder_information => {:text => 'folder:ManagedFolderInformation', :writable => true},
:permission_set => {:text => 'folder:PermissionSet', :writable => true},
:sharing_effective_rights => {:text => 'folder:SharingEffectiveRights', :writable => true},
:item_id => {:text => 'item:ItemId', :writable => true},
:parent_folder_id => {:text => 'item:ParentFolderId', :writable => true},
:item_class => {:text => 'item:ItemClass', :writable => true},
:mime_content => {:text => 'item:MimeContent', :writable => true},
:attachments => {:text => 'item:Attachments', :writable => true},
:subject => {:text => 'item:Subject', :writable => true},
:date_time_received => {:text => 'item:DateTimeReceived', :writable => true},
:in_reply_to => {:text => 'item:InReplyTo', :writable => true},
:internet_message_headers => {:text => 'item:InternetMessageHeaders', :writable => true},
:is_associated => {:text => 'item:IsAssociated', :writable => true},
:is_draft => {:text => 'item:IsDraft', :writable => true},
:is_from_me => {:text => 'item:IsFromMe', :writable => true},
:is_resend => {:text => 'item:IsResend', :writable => true},
:is_submitted => {:text => 'item:IsSubmitted', :writable => true},
:is_unmodified => {:text => 'item:IsUnmodified', :writable => true},
:date_time_sent => {:text => 'item:DateTimeSent', :writable => true},
:date_time_created => {:text => 'item:DateTimeCreated', :writable => true},
:body => {:text => 'item:Body', :writable => true},
:response_objects => {:text => 'item:ResponseObjects', :writable => true},
:sensitivity => {:text => 'item:Sensitivity', :writable => true},
:reminder_due_by => {:text => 'item:ReminderDueBy', :writable => true},
:reminder_is_set => {:text => 'item:ReminderIsSet', :writable => true},
:reminder_minutes_before_start => {:text => 'item:ReminderMinutesBeforeStart', :writable => true},
:display_to => {:text => 'item:DisplayTo', :writable => true},
:display_cc => {:text => 'item:DisplayCc', :writable => true},
:effective_rights => {:text => 'item:EffectiveRights', :writable => true},
:last_modified_name => {:text => 'item:LastModifiedName', :writable => true},
:last_modified_time => {:text => 'item:LastModifiedTime', :writable => true},
:unique_body => {:text => 'item:UniqueBody', :writable => true},
:web_client_read_form_query_string => {:text => 'item:WebClientReadFormQueryString', :writable => true},
:web_client_edit_form_query_string => {:text => 'item:WebClientEditFormQueryString', :writable => true},
:conversation_index => {:text => 'message:ConversationIndex', :writable => true},
:internet_message_id => {:text => 'message:InternetMessageId', :writable => true},
:is_read => {:text => 'message:IsRead', :writable => true},
:is_read_receipt_requested => {:text => 'message:IsReadReceiptRequested', :writable => true},
:is_delivery_receipt_requested => {:text => 'message:IsDeliveryReceiptRequested', :writable => true},
:references => {:text => 'message:References', :writable => true},
:reply_to => {:text => 'message:ReplyTo', :writable => true},
:from => {:text => 'message:From', :writable => true},
:sender => {:text => 'message:Sender', :writable => true},
:to_recipients => {:text => 'message:ToRecipients', :writable => true},
:cc_recipients => {:text => 'message:CcRecipients', :writable => true},
:bcc_recipients => {:text => 'message:BccRecipients', :writable => true},
:associated_calendar_item_id => {:text => 'meeting:AssociatedCalendarItemId', :writable => true},
:is_delegated => {:text => 'meeting:IsDelegated', :writable => true},
:is_out_of_date => {:text => 'meeting:IsOutOfDate', :writable => true},
:has_been_processed => {:text => 'meeting:HasBeenProcessed', :writable => true},
:response_type => {:text => 'meeting:ResponseType', :writable => true},
:meeting_request_type => {:text => 'meetingRequest:MeetingRequestType', :writable => true},
:intended_free_busy_status => {:text => 'meetingRequest:IntendedFreeBusyStatus', :writable => true},
:start => {:text => 'calendar:Start', :writable => true},
:end => {:text => 'calendar:End', :writable => true},
:original_start => {:text => 'calendar:OriginalStart', :writable => true},
:is_all_day_event => {:text => 'calendar:IsAllDayEvent', :writable => true},
:legacy_free_busy_status => {:text => 'calendar:LegacyFreeBusyStatus', :writable => true},
:location => {:text => 'calendar:Location', :writable => true},
:when => {:text => 'calendar:When', :writable => true},
:is_meeting => {:text => 'calendar:IsMeeting', :writable => true},
:is_cancelled => {:text => 'calendar:IsCancelled', :writable => true},
:meeting_request_was_sent => {:text => 'calendar:MeetingRequestWasSent', :writable => true},
:is_response_requested => {:text => 'calendar:IsResponseRequested', :writable => true},
:calendar_item_type => {:text => 'calendar:CalendarItemType', :writable => true},
:my_response_type => {:text => 'calendar:MyResponseType', :writable => true},
:organizer => {:text => 'calendar:Organizer', :writable => true},
:required_attendees => {:text => 'calendar:RequiredAttendees', :writable => true},
:optional_attendees => {:text => 'calendar:OptionalAttendees', :writable => true},
:resources => {:text => 'calendar:Resources', :writable => true},
:conflicting_meeting_count => {:text => 'calendar:ConflictingMeetingCount', :writable => true},
:adjacent_meeting_count => {:text => 'calendar:AdjacentMeetingCount', :writable => true},
:conflicting_meetings => {:text => 'calendar:ConflictingMeetings', :writable => true},
:adjacent_meetings => {:text => 'calendar:AdjacentMeetings', :writable => true},
:duration => {:text => 'calendar:Duration', :writable => true},
:time_zone => {:text => 'calendar:TimeZone', :writable => true},
:appointment_reply_time => {:text => 'calendar:AppointmentReplyTime', :writable => true},
:appointment_sequence_number => {:text => 'calendar:AppointmentSequenceNumber', :writable => true},
:appointment_state => {:text => 'calendar:AppointmentState', :writable => true},
:first_occurrence => {:text => 'calendar:FirstOccurrence', :writable => true},
:last_occurrence => {:text => 'calendar:LastOccurrence', :writable => true},
:modified_occurrences => {:text => 'calendar:ModifiedOccurrences', :writable => true},
:deleted_occurrences => {:text => 'calendar:DeletedOccurrences', :writable => true},
:meeting_time_zone => {:text => 'calendar:MeetingTimeZone', :writable => true},
:conference_type => {:text => 'calendar:ConferenceType', :writable => true},
:allow_new_time_proposal => {:text => 'calendar:AllowNewTimeProposal', :writable => true},
:is_online_meeting => {:text => 'calendar:IsOnlineMeeting', :writable => true},
:meeting_workspace_url => {:text => 'calendar:MeetingWorkspaceUrl', :writable => true},
:net_show_url => {:text => 'calendar:NetShowUrl', :writable => true},
:u_i_d => {:text => 'calendar:UID', :writable => true},
:recurrence_id => {:text => 'calendar:RecurrenceId', :writable => true},
:date_time_stamp => {:text => 'calendar:DateTimeStamp', :writable => true},
:start_time_zone => {:text => 'calendar:StartTimeZone', :writable => true},
:end_time_zone => {:text => 'calendar:EndTimeZone', :writable => true},
:actual_work => {:text => 'task:ActualWork', :writable => true},
:assigned_time => {:text => 'task:AssignedTime', :writable => true},
:billing_information => {:text => 'task:BillingInformation', :writable => true},
:change_count => {:text => 'task:ChangeCount', :writable => true},
:complete_date => {:text => 'task:CompleteDate', :writable => true},
:contacts => {:text => 'task:Contacts', :writable => true},
:delegation_state => {:text => 'task:DelegationState', :writable => true},
:delegator => {:text => 'task:Delegator', :writable => true},
:due_date => {:text => 'task:DueDate', :writable => true},
:is_assignment_editable => {:text => 'task:IsAssignmentEditable', :writable => true},
:is_complete => {:text => 'task:IsComplete', :writable => true},
:is_recurring => {:text => 'task:IsRecurring', :writable => true},
:is_team_task => {:text => 'task:IsTeamTask', :writable => true},
:owner => {:text => 'task:Owner', :writable => true},
:percent_complete => {:text => 'task:PercentComplete', :writable => true},
:recurrence => {:text => 'task:Recurrence', :writable => true},
:start_date => {:text => 'task:StartDate', :writable => true},
:status => {:text => 'task:Status', :writable => true},
:status_description => {:text => 'task:StatusDescription', :writable => true},
:total_work => {:text => 'task:TotalWork', :writable => true},
:assistant_name => {:text => 'contacts:AssistantName', :writable => true},
:birthday => {:text => 'contacts:Birthday', :writable => true},
:birthday_local => {:text => 'contacts:BirthdayLocal', :writable => true},
:business_home_page => {:text => 'contacts:BusinessHomePage', :writable => true},
:children => {:text => 'contacts:Children', :writable => true},
:companies => {:text => 'contacts:Companies', :writable => true},
:company_name => {:text => 'contacts:CompanyName', :writable => true},
:complete_name => {:text => 'contacts:CompleteName', :writable => true},
:contact_source => {:text => 'contacts:ContactSource', :writable => true},
:culture => {:text => 'contacts:Culture', :writable => true},
:department => {:text => 'contacts:Department', :writable => true},
:display_name => {:text => 'contacts:DisplayName', :writable => true},
:email_addresses => {:ftype => :indexed_field_uRI, :text => 'contacts:EmailAddress', :writable => true},
:file_as => {:text => 'contacts:FileAs', :writable => true},
:file_as_mapping => {:text => 'contacts:FileAsMapping', :writable => true},
:generation => {:text => 'contacts:Generation', :writable => true},
:given_name => {:text => 'contacts:GivenName', :writable => true},
:has_picture => {:text => 'contacts:HasPicture', :writable => true},
:im_addresses => {:text => 'contacts:ImAddresses', :writable => true},
:initials => {:text => 'contacts:Initials', :writable => true},
:job_title => {:text => 'contacts:JobTitle', :writable => true},
:manager => {:text => 'contacts:Manager', :writable => true},
:middle_name => {:text => 'contacts:MiddleName', :writable => true},
:mileage => {:text => 'contacts:Mileage', :writable => true},
:nickname => {:text => 'contacts:Nickname', :writable => true},
:office_location => {:text => 'contacts:OfficeLocation', :writable => true},
:phone_numbers => {:ftype => :indexed_field_uRI, :text => 'contacts:PhoneNumber', :writable => true},
:physical_addresses => {:text => 'contacts:PhysicalAddresses', :writable => true},
:postal_address_index => {:text => 'contacts:PostalAddressIndex', :writable => true},
:profession => {:text => 'contacts:Profession', :writable => true},
:spouse_name => {:text => 'contacts:SpouseName', :writable => true},
:surname => {:text => 'contacts:Surname', :writable => true},
:wedding_anniversary => {:text => 'contacts:WeddingAnniversary', :writable => true},
:wedding_anniversary_local => {:text => 'contacts:WeddingAnniversaryLocal', :writable => true},
:members => {:text => 'distributionlist:Members', :writable => true},
:posted_time => {:text => 'postitem:PostedTime', :writable => true},
:conversation_id => {:text => 'conversation:ConversationId', :writable => true},
:conversation_topic => {:text => 'conversation:ConversationTopic', :writable => true},
:unique_recipients => {:text => 'conversation:UniqueRecipients', :writable => true},
:global_unique_recipients => {:text => 'conversation:GlobalUniqueRecipients', :writable => true},
:unique_unread_senders => {:text => 'conversation:UniqueUnreadSenders', :writable => true},
:global_unique_unread_senders => {:text => 'conversation:GlobalUniqueUnreadSenders', :writable => true},
:unique_senders => {:text => 'conversation:UniqueSenders', :writable => true},
:global_unique_senders => {:text => 'conversation:GlobalUniqueSenders', :writable => true},
:last_delivery_time => {:text => 'conversation:LastDeliveryTime', :writable => true},
:global_last_delivery_time => {:text => 'conversation:GlobalLastDeliveryTime', :writable => true},
:categories => {:text => 'conversation:Categories', :writable => true},
:global_categories => {:text => 'conversation:GlobalCategories', :writable => true},
:flag_status => {:text => 'conversation:FlagStatus', :writable => true},
:global_flag_status => {:text => 'conversation:GlobalFlagStatus', :writable => true},
:has_attachments => {:text => 'conversation:HasAttachments', :writable => true},
:global_has_attachments => {:text => 'conversation:GlobalHasAttachments', :writable => true},
:message_count => {:text => 'conversation:MessageCount', :writable => true},
:global_message_count => {:text => 'conversation:GlobalMessageCount', :writable => true},
:unread_count => {:text => 'conversation:UnreadCount', :writable => true},
:global_unread_count => {:text => 'conversation:GlobalUnreadCount', :writable => true},
:size => {:text => 'conversation:Size', :writable => true},
:global_size => {:text => 'conversation:GlobalSize', :writable => true},
:item_classes => {:text => 'conversation:ItemClasses', :writable => true},
:global_item_classes => {:text => 'conversation:GlobalItemClasses', :writable => true},
:importance => {:text => 'conversation:Importance', :writable => true},
:global_importance => {:text => 'conversation:GlobalImportance', :writable => true},
:item_ids => {:text => 'conversation:ItemIds', :writable => true},
:global_item_ids => {:text => 'conversation:GlobalItemIds', :writable => true}
}
end
end
end
| 76.815166 | 113 | 0.613956 |
269e34133c299da1a6624afb4c6eea555ac39c14 | 1,106 | # 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 "googleauth"
module Google
module Ads
module GoogleAds
module V8
module Services
module AdGroupAdLabelService
# Credentials for the AdGroupAdLabelService API.
class Credentials < ::Google::Auth::Credentials
self.scope = [
"https://www.googleapis.com/auth/adwords"
]
end
end
end
end
end
end
end
| 28.358974 | 74 | 0.676311 |
384e793dfa538578d5386f0ec955fe58079d963a | 808 | require 'spec_helper'
require 'r10k/puppetfile'
describe R10K::Puppetfile do
subject do
described_class.new(
'/some/nonexistent/basedir'
)
end
describe "the default moduledir" do
it "is the basedir joined with '/modules' path" do
expect(subject.moduledir).to eq '/some/nonexistent/basedir/modules'
end
end
describe "setting moduledir" do
it "changes to given moduledir if it is an absolute path" do
subject.set_moduledir('/absolute/path/moduledir')
expect(subject.moduledir).to eq '/absolute/path/moduledir'
end
it "joins the basedir with the given moduledir if it is a relative path" do
subject.set_moduledir('relative/moduledir')
expect(subject.moduledir).to eq '/some/nonexistent/basedir/relative/moduledir'
end
end
end
| 26.933333 | 84 | 0.712871 |
e98205b0602336160f31956f5bc72067eddc8b1c | 2,552 | require "byebug"
ENV["RACK_ENV"] = "test"
SPEC_ROOT = Pathname(__FILE__).dirname
Dir[SPEC_ROOT.join("support/*.rb").to_s].each(&method(:require))
Dir[SPEC_ROOT.join("shared/*.rb").to_s].each(&method(:require))
require SPEC_ROOT.join("../system/streakist/container")
RSpec.configure do |config|
config.disable_monkey_patching!
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4.
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on a
# real object. This is generally recommended, and will default to `true`
# in RSpec 4.
mocks.verify_partial_doubles = true
end
# These two settings work together to allow you to limit a spec run to
# individual examples or groups you care about by tagging them with `:focus`
# metadata. When nothing is tagged with `:focus`, all examples get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Allows RSpec to persist some state between runs in order to support the
# `--only-failures` and `--next-failure` CLI options.
config.example_status_persistence_file_path = "spec/examples.txt"
# This setting enables warnings. It's recommended, but in some cases may be
# too noisy due to issues in dependencies.
# config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the end of the spec
# run, to help surface which specs are running particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
end
| 38.089552 | 78 | 0.740204 |
1c051e86c50ea3209bf2c84e93bc24f59afc9155 | 334 | class CreateJudgeTeamRoles < ActiveRecord::Migration[5.1]
def change
create_table :judge_team_roles, comment: "Defines roles for individual members of judge teams" do |t|
t.string :type
t.column :organizations_user_id, :integer
t.index :organizations_user_id, unique: true
t.timestamps
end
end
end
| 30.363636 | 105 | 0.724551 |
62b1b0705bf7a0c8d24d782fb01783707a755dda | 25,731 | require 'spec_helper'
require 'yaml'
describe PDK::Module::TemplateDir do
subject(:template_dir) do
described_class.new(uri, module_metadata, true) do |foo|
# block does nothing
end
end
let(:path_or_url) { File.join('/', 'path', 'to', 'templates') }
let(:uri) { PDK::Util::TemplateURI.new(path_or_url) }
let(:tmp_path) { File.join('/', 'tmp', 'path') }
let(:module_metadata) do
{
'name' => 'foo-bar',
'version' => '0.1.0',
}
end
let(:config_defaults) do
<<-EOS
appveyor.yml:
environment:
PUPPET_GEM_VERSION: "~> 4.0"
foo:
attr:
- val: 1
EOS
end
before(:each) do
allow(PDK::Util::Git).to receive(:work_tree?).with(path_or_url).and_return(false)
allow(PDK::Util::Git).to receive(:work_tree?).with(uri.shell_path).and_return(false)
end
describe '.new' do
context 'when not passed a block' do
it 'raises an ArgumentError' do
expect {
described_class.new(uri, module_metadata)
}.to raise_error(ArgumentError, %r{must be initialized with a block}i)
end
end
context 'when not initialized with a PDK::Util::TemplateURI' do
it 'raises an ArgumentError' do
expect {
described_class.new(path_or_url, module_metadata) {}
}.to raise_error(ArgumentError, %r{must be initialized with a PDK::Util::TemplateURI}i)
end
end
end
describe '#validate_module_template!' do
let(:moduleroot) { File.join(path_or_url, 'moduleroot') }
let(:moduleroot_init) { File.join(path_or_url, 'moduleroot_init') }
before(:each) do
allow(File).to receive(:directory?).with(anything).and_return(true)
end
context 'when the template path is a directory' do
before(:each) do
allow(File).to receive(:directory?).with(path_or_url).and_return(true)
end
context 'and the template contains a moduleroot directory' do
before(:each) do
allow(File).to receive(:directory?).with(moduleroot).and_return(true)
end
context 'and a moduleroot_init directory' do
before(:each) do
allow(File).to receive(:directory?).with(moduleroot_init).and_return(true)
end
it 'does not raise an error' do
expect { described_class.new(uri, module_metadata) {} }.not_to raise_error
end
end
context 'but not a moduleroot_init directory' do
before(:each) do
allow(File).to receive(:directory?).with(moduleroot_init).and_return(false)
end
it 'raises an ArgumentError' do
expect {
described_class.new(uri, module_metadata) {}
}.to raise_error(ArgumentError, %r{does not contain a 'moduleroot_init/'})
end
end
end
context 'and the template does not contain a moduleroot directory' do
before(:each) do
allow(File).to receive(:directory?).with(moduleroot).and_return(false)
end
it 'raises an ArgumentError' do
expect {
described_class.new(uri, module_metadata) {}
}.to raise_error(ArgumentError, %r{does not contain a 'moduleroot/'})
end
end
end
context 'when the template path is not a directory' do
before(:each) do
allow(File).to receive(:directory?).with(path_or_url).and_return(false)
allow(PDK::Util).to receive(:package_install?).and_return(false)
end
context 'and it specifies an deprecated built-in template' do
before(:each) do
# rubocop:disable RSpec/AnyInstance
allow(PDK::Util).to receive(:package_install?).and_return(true)
allow(File).to receive(:fnmatch?).with(anything, path_or_url).and_return(true)
allow(PDK::Util).to receive(:package_cachedir).and_return(File.join('/', 'path', 'to', 'package', 'cachedir'))
allow_any_instance_of(described_class).to receive(:clone_template_repo).and_return(path_or_url)
allow(PDK::Util::Git).to receive(:repo?).with(path_or_url).and_return(true)
allow(FileUtils).to receive(:remove_dir)
allow(PDK::Util::Git).to receive(:git).with('--git-dir', anything, 'describe', '--all', '--long', '--always', anything).and_return(stdout: 'ref', exit_code: 0)
# rubocop:enable RSpec/AnyInstance
end
it 'raises an ArgumentError' do
expect {
described_class.new(uri, module_metadata) {}
}.to raise_error(ArgumentError, %r{built-in template has substantially changed})
end
end
it 'raises an ArgumentError' do
expect {
described_class.new(uri, module_metadata) {}
}.to raise_error(ArgumentError, %r{is not a directory})
end
end
end
describe '#checkout_template_ref' do
let(:path) { File.join('/', 'path', 'to', 'workdir') }
let(:ref) { '12345678' }
let(:full_ref) { '123456789abcdef' }
before(:each) do
# rubocop:disable RSpec/AnyInstance
allow_any_instance_of(described_class).to receive(:clone_template_repo).and_return(path)
allow(PDK::Util::Git).to receive(:repo?).with(anything).and_return(true)
allow(FileUtils).to receive(:remove_dir).with(path)
allow_any_instance_of(described_class).to receive(:validate_module_template!)
allow(PDK::Util::Git).to receive(:describe).and_return('git-ref')
# rubocop:enable RSpec/AnyInstance
end
context 'when the template workdir is clean' do
before(:each) do
allow(PDK::Util::Git).to receive(:work_dir_clean?).with(path).and_return(true)
allow(Dir).to receive(:chdir).with(path).and_yield
allow(PDK::Util::Git).to receive(:ls_remote).with(path, ref).and_return(full_ref)
end
context 'and the git reset succeeds' do
before(:each) do
allow(PDK::Util::Git).to receive(:git).with('reset', '--hard', full_ref).and_return(exit_code: 0)
end
it 'does not raise an error' do
expect {
template_dir.checkout_template_ref(path, ref)
}.not_to raise_error
end
end
context 'and the git reset fails' do
let(:result) { { exit_code: 1, stderr: 'stderr', stdout: 'stdout' } }
before(:each) do
allow(PDK::Util::Git).to receive(:git).with('reset', '--hard', full_ref).and_return(result)
end
it 'raises a FatalError' do
expect(logger).to receive(:error).with(result[:stdout])
expect(logger).to receive(:error).with(result[:stderr])
expect {
template_dir.checkout_template_ref(path, ref)
}.to raise_error(PDK::CLI::FatalError, %r{unable to set head of git repository}i)
end
end
end
context 'when the template workdir is not clean' do
before(:each) do
allow(PDK::Util::Git).to receive(:work_dir_clean?).with(path).and_return(false)
end
after(:each) do
template_dir.checkout_template_ref(path, ref)
end
it 'warns the user' do
expect(logger).to receive(:warn).with(a_string_matching(%r{uncommitted changes found}i))
end
end
end
context 'with a valid template path' do
it 'returns config hash with module metadata' do
allow(File).to receive(:directory?).with(anything).and_return(true)
allow(PDK::Util::Git).to receive(:repo?).with(path_or_url).and_return(false)
allow(PDK::Util).to receive(:make_tmpdir_name).with('pdk-templates').and_return(tmp_path)
allow(PDK::CLI::Exec).to receive(:git).with('clone', path_or_url, tmp_path).and_return(exit_code: 0)
allow(File).to receive(:file?).with(anything).and_return(File.join(path_or_url, 'config_defaults.yml')).and_return(true)
allow(File).to receive(:read).with(File.join(path_or_url, 'config_defaults.yml')).and_return(config_defaults)
allow(Dir).to receive(:rmdir).with(tmp_path).and_return(0)
allow(described_class).to receive(:new).with(uri, module_metadata).and_yield(template_dir)
expect(template_dir.object_config).to include('module_metadata' => module_metadata)
end
end
it 'has a metadata method' do
expect(described_class.instance_methods(false)).to include(:metadata)
end
describe '.files_in_template(dirs)' do
context 'when passing in an empty directory' do
let(:dirs) { ['/the/file/is/here'] }
before(:each) do
allow(Dir).to receive(:exist?).with('/the/file/is/here').and_return true
end
it 'returns an empty list' do
expect(described_class.files_in_template(dirs)).to eq({})
end
end
context 'when passing in a non-existant directory' do
let(:dirs) { ['/the/file/is/nothere'] }
before(:each) do
allow(Dir).to receive(:exists?).with('/the/file/is/nothere').and_return false
end
it 'raises an error' do
expect { described_class.files_in_template(dirs) }.to raise_error(ArgumentError, %r{The directory '/the/file/is/nothere' doesn't exist})
end
end
context 'when passing in a directory with a single file' do
let(:dirs) { ['/here/moduleroot'] }
before(:each) do
allow(Dir).to receive(:exist?).with('/here/moduleroot').and_return true
allow(File).to receive(:file?).with('/here/moduleroot/filename').and_return true
allow(Dir).to receive(:glob).with('/here/moduleroot/**/*', File::FNM_DOTMATCH).and_return ['/here/moduleroot/filename']
end
it 'returns the file name' do
expect(described_class.files_in_template(dirs)).to eq('filename' => '/here/moduleroot')
end
end
context 'when passing in a directory with more than one file' do
let(:dirs) { ['/here/moduleroot'] }
before(:each) do
allow(Dir).to receive(:exist?).with('/here/moduleroot').and_return true
allow(File).to receive(:file?).with('/here/moduleroot/filename').and_return true
allow(File).to receive(:file?).with('/here/moduleroot/filename2').and_return true
allow(Dir).to receive(:glob).with('/here/moduleroot/**/*', File::FNM_DOTMATCH).and_return ['/here/moduleroot/filename', '/here/moduleroot/filename2']
end
it 'returns both the file names' do
expect(described_class.files_in_template(dirs)).to eq('filename' => '/here/moduleroot', 'filename2' => '/here/moduleroot')
end
end
context 'when passing in more than one directory with a file' do
let(:dirs) { ['/path/to/templates/moduleroot', '/path/to/templates/moduleroot_init'] }
before(:each) do
allow(Dir).to receive(:exist?).with('/path/to/templates').and_return true
allow(Dir).to receive(:exist?).with('/path/to/templates/moduleroot').and_return true
allow(Dir).to receive(:exist?).with('/path/to/templates/moduleroot_init').and_return true
allow(File).to receive(:file?).with('/path/to/templates/moduleroot/.').and_return false
allow(File).to receive(:file?).with('/path/to/templates/moduleroot/filename').and_return true
allow(File).to receive(:file?).with('/path/to/templates/moduleroot_init/filename2').and_return true
allow(Dir).to receive(:glob).with('/path/to/templates/moduleroot/**/*', File::FNM_DOTMATCH).and_return ['/path/to/templates/moduleroot/.', '/path/to/templates/moduleroot/filename']
allow(Dir).to receive(:glob).with('/path/to/templates/moduleroot_init/**/*', File::FNM_DOTMATCH).and_return ['/path/to/templates/moduleroot_init/filename2']
end
it 'returns the file names from both directories' do
expect(described_class.files_in_template(dirs)).to eq('filename' => '/path/to/templates/moduleroot',
'filename2' => '/path/to/templates/moduleroot_init')
end
end
end
describe '.render(template_files)' do
before(:each) do
allow(File).to receive(:directory?).with(anything).and_return(true)
allow(PDK::Util::Git).to receive(:repo?).with(path_or_url).and_return(false)
allow(PDK::Util).to receive(:make_tmpdir_name).with('pdk-templates').and_return(tmp_path)
allow(PDK::CLI::Exec).to receive(:git).with('clone', path_or_url, tmp_path).and_return(exit_code: 0)
end
context 'when passing in a template file' do
let(:template_file) { instance_double('PDK::TemplateFile', 'filename.erb') }
let(:template_files) { { 'filename.erb' => 'file/is/here/' } }
before(:each) do
allow(described_class).to receive(:config_for).with('filename').and_return true
allow(PDK::TemplateFile).to receive(:new).with('file/is/here/filename.erb', configs: true).and_return template_file
allow(template_file).to receive(:render).and_return template_file
allow(described_class).to receive(:render).and_return('filename.erb' => 'file/is/here/')
end
it 'renders the template file and returns relevant values' do
expect(described_class.render(template_files)).to eq('filename.erb' => 'file/is/here/')
end
end
context 'when passing in two template files in the same location' do
let(:template_file) { instance_double('PDK::TemplateFile', 'filename.erb') }
let(:template_file2) { instance_double('PDK::TemplateFile', 'filename2.erb') }
let(:template_files) { { 'filename.erb' => 'file/is/here/', 'filename2.erb' => 'file/is/here/' } }
before(:each) do
allow(described_class).to receive(:config_for).with('filename').and_return true
allow(PDK::TemplateFile).to receive(:new).with('file/is/here/filename.erb', configs: true).and_return template_file
allow(template_file).to receive(:render).and_return template_file
allow(described_class).to receive(:config_for).with('filename2').and_return true
allow(PDK::TemplateFile).to receive(:new).with('file/is/here/filename2.erb', configs: true).and_return template_file
allow(template_file).to receive(:render).and_return template_file2
allow(described_class).to receive(:render).and_return('filename.erb' => 'file/is/here/', 'filename2.erb' => 'file/is/here/')
end
it 'renders the template file and returns relevant values' do
expect(described_class.render(template_files)).to eq('filename.erb' => 'file/is/here/', 'filename2.erb' => 'file/is/here/')
end
end
context 'when passing in two template files in different directories' do
let(:template_file) { instance_double('PDK::TemplateFile', 'filename.erb') }
let(:template_file2) { instance_double('PDK::TemplateFile', 'filename2.erb') }
let(:template_files) { { 'filename.erb' => 'file/is/here/', 'filename2.erb' => 'file/is/here/' } }
before(:each) do
allow(described_class).to receive(:config_for).with('filename').and_return true
allow(PDK::TemplateFile).to receive(:new).with('file/is/here/filename.erb', configs: true).and_return template_file
allow(template_file).to receive(:render).and_return template_file
allow(described_class).to receive(:config_for).with('filename2').and_return true
allow(PDK::TemplateFile).to receive(:new).with('file/is/where/filename2.erb', configs: true).and_return template_file
allow(template_file2).to receive(:render).and_return template_file2
allow(described_class).to receive(:render).and_return('filename.erb' => 'file/is/here/', 'filename2.erb' => 'file/is/where/')
end
it 'renders the template file and returns relevant values' do
expect(described_class.render(template_files)).to eq('filename.erb' => 'file/is/here/', 'filename2.erb' => 'file/is/where/')
end
end
end
describe '.config_for(dest_path)' do
before(:each) do
allow(Gem).to receive(:win_platform?).and_return(false)
allow(File).to receive(:directory?).with(anything).and_return(true)
allow(PDK::Util::Git).to receive(:repo?).with(path_or_url).and_return(false)
allow(PDK::Util).to receive(:make_tmpdir_name).with('pdk-templates').and_return(tmp_path)
allow(PDK::CLI::Exec).to receive(:git).with('clone', path_or_url, tmp_path).and_return(exit_code: 0)
allow(File).to receive(:file?).with(anything).and_return(File.join(path_or_url, 'config_defaults.yml')).and_return(true)
allow(File).to receive(:read).with(File.join(path_or_url, 'config_defaults.yml')).and_return(config_defaults)
allow(File).to receive(:readable?).with(File.join(path_or_url, 'config_defaults.yml')).and_return(true)
allow(YAML).to receive(:safe_load).with(config_defaults, [], [], true).and_return config_hash
end
context 'when the module has a valid .sync.yml file' do
let(:yaml_text) do
<<-EOF
appveyor.yml:
environment:
PUPPET_GEM_VERSION: "~> 5.0"
.travis.yml:
extras:
- rvm: 2.1.9
foo:
attr:
- val: 3
.project:
delete: true
.gitlab-ci.yml:
unmanaged: true
EOF
end
let(:yaml_hash) do
YAML.load(yaml_text) # rubocop:disable Security/YAMLLoad
end
let(:config_hash) do
YAML.load(config_defaults) # rubocop:disable Security/YAMLLoad
end
before(:each) do
allow(File).to receive(:file?).with('/path/to/module/.sync.yml').and_return(true)
allow(File).to receive(:readable?).with('/path/to/module/.sync.yml').and_return(true)
allow(File).to receive(:read).with('/path/to/module/.sync.yml').and_return(yaml_text)
allow(YAML).to receive(:safe_load).with(yaml_text, [], [], true).and_return(yaml_hash)
allow(PDK::Util).to receive(:module_root).and_return('/path/to/module')
end
it 'absorbs config' do
expect(template_dir.config_for(path_or_url)).to eq('module_metadata' => module_metadata,
'appveyor.yml' => { 'environment' => { 'PUPPET_GEM_VERSION' => '~> 5.0' } },
'.travis.yml' => { 'extras' => [{ 'rvm' => '2.1.9' }] },
'foo' => { 'attr' => [{ 'val' => 1 }, { 'val' => 3 }] },
'.project' => { 'delete' => true },
'.gitlab-ci.yml' => { 'unmanaged' => true })
end
context 'contains a knockout prefix' do
let(:config_defaults) do
<<-EOS
appveyor.yml:
environment:
PUPPET_GEM_VERSION: "~> 4.0"
foo:
attr:
- val: 1
ko:
- valid
- removed
EOS
end
let(:yaml_text) do
<<-EOF
appveyor.yml:
environment:
PUPPET_GEM_VERSION: "~> 5.0"
.travis.yml:
extras:
- rvm: 2.1.9
foo:
attr:
- val: 3
ko:
- ---removed
.project:
delete: true
.gitlab-ci.yml:
unmanaged: true
EOF
end
let(:yaml_hash) do
YAML.load(yaml_text) # rubocop:disable Security/YAMLLoad
end
let(:config_hash) do
YAML.load(config_defaults) # rubocop:disable Security/YAMLLoad
end
it 'removes the knocked out options' do
expect(template_dir.config_for(path_or_url)).to eq('module_metadata' => module_metadata,
'appveyor.yml' => { 'environment' => { 'PUPPET_GEM_VERSION' => '~> 5.0' } },
'.travis.yml' => { 'extras' => [{ 'rvm' => '2.1.9' }] },
'foo' => { 'attr' => [{ 'val' => 1 }, { 'val' => 3 }], 'ko' => ['valid'] },
'.project' => { 'delete' => true },
'.gitlab-ci.yml' => { 'unmanaged' => true })
end
end
end
context 'when the module has an invalid .sync.yml file' do
let(:yaml_text) do
<<-EOF
appveyor.yml:
environment:
PUPPET_GEM_VERSION: "~> 5.0
EOF
end
let(:config_hash) do
YAML.load(config_defaults) # rubocop:disable Security/YAMLLoad
end
before(:each) do
allow(File).to receive(:file?).with('/path/to/module/.sync.yml').and_return true
allow(File).to receive(:readable?).with('/path/to/module/.sync.yml').and_return true
allow(File).to receive(:read).with('/path/to/module/.sync.yml').and_return yaml_text
allow(YAML).to receive(:safe_load).with(yaml_text, [], [], true).and_call_original
allow(PDK::Util).to receive(:module_root).and_return('/path/to/module')
end
it 'logs a warning' do
expect(logger).to receive(:warn).with(%r{not a valid yaml file}i)
template_dir.config_for(path_or_url)
end
it 'returns default config' do
expected = { 'module_metadata' => module_metadata }.merge(config_hash)
expect(template_dir.config_for(path_or_url)).to eq(expected)
end
end
end
describe '.metadata' do
before(:each) do
allow(File).to receive(:directory?).with(anything).and_return(true)
allow(PDK::Util::Git).to receive(:repo?).with(path_or_url).and_return(true)
allow(PDK::Util).to receive(:default_template_url).and_return(path_or_url)
allow(PDK::Util::TemplateURI).to receive(:default_template_ref).and_return('default-ref')
allow(PDK::Util).to receive(:make_tmpdir_name).with('pdk-templates').and_return(tmp_path)
allow(Dir).to receive(:chdir).with(tmp_path).and_yield
allow(PDK::Util::Git).to receive(:git).with('clone', path_or_url, tmp_path).and_return(exit_code: 0)
allow(PDK::Util::Git).to receive(:git).with('reset', '--hard', 'default-sha').and_return(exit_code: 0)
allow(FileUtils).to receive(:remove_dir).with(tmp_path)
allow(PDK::Util::Git).to receive(:git).with('--git-dir', anything, 'describe', '--all', '--long', '--always', 'default-sha').and_return(exit_code: 0, stdout: '1234abcd')
allow(PDK::Util::Git).to receive(:git).with('--work-tree', anything, '--git-dir', anything, 'status', '--untracked-files=no', '--porcelain', anything).and_return(exit_code: 0, stdout: '')
allow(PDK::Util::Git).to receive(:git).with('ls-remote', '--refs', 'file:///tmp/path', 'default-ref').and_return(exit_code: 0, stdout:
"default-sha\trefs/heads/default-ref\n" \
"default-sha\trefs/remotes/origin/default-ref")
allow(PDK::Util::Version).to receive(:version_string).and_return('0.0.0')
allow(PDK::Util).to receive(:canonical_path).with(tmp_path).and_return(tmp_path)
allow(PDK::Util).to receive(:development_mode?).and_return(false)
end
context 'pdk data' do
it 'includes the PDK version and template info' do
expect(template_dir.metadata).to include('pdk-version' => '0.0.0', 'template-url' => path_or_url, 'template-ref' => '1234abcd')
end
end
end
describe 'custom template' do
before(:each) do
allow(File).to receive(:directory?).with(anything).and_return(true)
allow(PDK::Util::Git).to receive(:repo?).with(path_or_url).and_return(true)
allow(PDK::Util).to receive(:default_template_url).and_return('default-url')
allow(PDK::Util::TemplateURI).to receive(:default_template_ref).and_return('default-ref')
allow(PDK::Util).to receive(:make_tmpdir_name).with('pdk-templates').and_return(tmp_path)
allow(Dir).to receive(:chdir).with(tmp_path).and_yield
allow(PDK::Util::Git).to receive(:git).with('clone', path_or_url, tmp_path).and_return(exit_code: 0)
allow(PDK::Util::Git).to receive(:git).with('reset', '--hard', 'default-sha').and_return(exit_code: 0)
allow(FileUtils).to receive(:remove_dir).with(tmp_path)
allow(PDK::Util::Git).to receive(:git).with('--git-dir', anything, 'describe', '--all', '--long', '--always', 'default-sha').and_return(exit_code: 0, stdout: '1234abcd')
allow(PDK::Util::Git).to receive(:git).with('--work-tree', anything, '--git-dir', anything, 'status', '--untracked-files=no', '--porcelain', anything).and_return(exit_code: 0, stdout: '')
allow(PDK::Util::Git).to receive(:git).with('ls-remote', '--refs', 'file:///tmp/path', 'default-ref').and_return(exit_code: 0, stdout:
"default-sha\trefs/heads/default-ref\n" \
"default-sha\trefs/remotes/origin/default-ref")
allow(PDK::Util::Version).to receive(:version_string).and_return('0.0.0')
allow(PDK::Util).to receive(:canonical_path).with(tmp_path).and_return(tmp_path)
allow(PDK::Util).to receive(:development_mode?).and_return(false)
end
context 'pdk data' do
it 'includes the PDK version and template info' do
expect(template_dir.metadata).to include('pdk-version' => '0.0.0', 'template-url' => path_or_url, 'template-ref' => '1234abcd')
end
end
end
end
| 45.62234 | 193 | 0.617077 |
b9624c158aa8092cb746f0a4e4e154e6359a464c | 1,570 | # frozen_string_literal: true
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'carrierwave/google/storage/version'
Gem::Specification.new do |spec|
spec.name = 'carrierwave-google-storage'
spec.version = Carrierwave::Google::Storage::VERSION
spec.authors = ['Jasdeep Singh']
spec.email = ['[email protected]']
spec.summary = %q(Use gcloud for Google Cloud Storage support in CarrierWave.)
spec.description = %q(A slimmer alternative to using Fog for Google Cloud Storage support in CarrierWave. Heavily inspired from carrierwave-aws)
spec.homepage = 'https://github.com/metaware/carrierwave-google-storage'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.required_ruby_version = ">= 2.4"
spec.add_dependency 'carrierwave', '~> 2.0'
spec.add_dependency 'google-cloud-storage', '~> 1.24'
if RUBY_VERSION >= '2.2.2'
spec.add_dependency 'activemodel', '>= 3.2.0'
else
spec.add_dependency 'activemodel', '~> 4.2.7'
end
spec.add_development_dependency 'bundler', '~> 2.0'
spec.add_development_dependency 'pry', '~> 0.10.3'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.0'
spec.add_development_dependency 'uri-query_params', '~> 0.7.1'
end
| 39.25 | 148 | 0.67707 |
e279813abf508bd11bdb3967e25180e298b3f3f6 | 804 | # frozen_string_literal: true
module FriendlyShipping
class Carrier
attr_reader :id, :name, :code, :shipping_methods, :balance, :data
# @param [Integer] id The carrier's ID
# @param [String] name The carrier's name
# @param [String] code The carrier's unique code
# @param [Array] shipping_methods The shipping methods available on this carrier
# @param [Float] balance The remaining balance for this carrier
# @param [Hash] data Additional data related to this carrier
def initialize(id: nil, name: nil, code: nil, shipping_methods: [], balance: nil, data: {})
@id = id
@name = name
@code = code
@shipping_methods = shipping_methods
@balance = balance
@data = data
end
def ==(other)
id == other.id
end
end
end
| 29.777778 | 95 | 0.656716 |
21128b52cb44f7fed6ae17ef3c643db743a5e409 | 11,245 | # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'date'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# Phase 1 Configuration Details
class Core::Models::PhaseOneConfigDetails
AUTHENTICATION_ALGORITHM_ENUM = [
AUTHENTICATION_ALGORITHM_SHA2_384 = 'SHA2_384'.freeze,
AUTHENTICATION_ALGORITHM_SHA2_256 = 'SHA2_256'.freeze,
AUTHENTICATION_ALGORITHM_SHA1_96 = 'SHA1_96'.freeze
].freeze
ENCRYPTION_ALGORITHM_ENUM = [
ENCRYPTION_ALGORITHM_AES_256_CBC = 'AES_256_CBC'.freeze,
ENCRYPTION_ALGORITHM_AES_192_CBC = 'AES_192_CBC'.freeze,
ENCRYPTION_ALGORITHM_AES_128_CBC = 'AES_128_CBC'.freeze
].freeze
DIFFIE_HELMAN_GROUP_ENUM = [
DIFFIE_HELMAN_GROUP_GROUP2 = 'GROUP2'.freeze,
DIFFIE_HELMAN_GROUP_GROUP5 = 'GROUP5'.freeze,
DIFFIE_HELMAN_GROUP_GROUP14 = 'GROUP14'.freeze,
DIFFIE_HELMAN_GROUP_GROUP19 = 'GROUP19'.freeze,
DIFFIE_HELMAN_GROUP_GROUP20 = 'GROUP20'.freeze,
DIFFIE_HELMAN_GROUP_GROUP24 = 'GROUP24'.freeze
].freeze
# Indicates whether custom phase one configuration is enabled.
# @return [BOOLEAN]
attr_accessor :is_custom_phase_one_config
# Phase one authentication algorithm supported during tunnel negotiation.
#
# @return [String]
attr_reader :authentication_algorithm
# Phase one encryption algorithm supported during tunnel negotiation.
#
# @return [String]
attr_reader :encryption_algorithm
# Phase One Diffie Hellman group supported during tunnel negotiation.
#
# @return [String]
attr_reader :diffie_helman_group
# IKE session key lifetime in seconds for IPSec phase one.
# @return [Integer]
attr_accessor :lifetime_in_seconds
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'is_custom_phase_one_config': :'isCustomPhaseOneConfig',
'authentication_algorithm': :'authenticationAlgorithm',
'encryption_algorithm': :'encryptionAlgorithm',
'diffie_helman_group': :'diffieHelmanGroup',
'lifetime_in_seconds': :'lifetimeInSeconds'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'is_custom_phase_one_config': :'BOOLEAN',
'authentication_algorithm': :'String',
'encryption_algorithm': :'String',
'diffie_helman_group': :'String',
'lifetime_in_seconds': :'Integer'
# 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 [BOOLEAN] :is_custom_phase_one_config The value to assign to the {#is_custom_phase_one_config} property
# @option attributes [String] :authentication_algorithm The value to assign to the {#authentication_algorithm} property
# @option attributes [String] :encryption_algorithm The value to assign to the {#encryption_algorithm} property
# @option attributes [String] :diffie_helman_group The value to assign to the {#diffie_helman_group} property
# @option attributes [Integer] :lifetime_in_seconds The value to assign to the {#lifetime_in_seconds} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.is_custom_phase_one_config = attributes[:'isCustomPhaseOneConfig'] unless attributes[:'isCustomPhaseOneConfig'].nil?
raise 'You cannot provide both :isCustomPhaseOneConfig and :is_custom_phase_one_config' if attributes.key?(:'isCustomPhaseOneConfig') && attributes.key?(:'is_custom_phase_one_config')
self.is_custom_phase_one_config = attributes[:'is_custom_phase_one_config'] unless attributes[:'is_custom_phase_one_config'].nil?
self.authentication_algorithm = attributes[:'authenticationAlgorithm'] if attributes[:'authenticationAlgorithm']
raise 'You cannot provide both :authenticationAlgorithm and :authentication_algorithm' if attributes.key?(:'authenticationAlgorithm') && attributes.key?(:'authentication_algorithm')
self.authentication_algorithm = attributes[:'authentication_algorithm'] if attributes[:'authentication_algorithm']
self.encryption_algorithm = attributes[:'encryptionAlgorithm'] if attributes[:'encryptionAlgorithm']
raise 'You cannot provide both :encryptionAlgorithm and :encryption_algorithm' if attributes.key?(:'encryptionAlgorithm') && attributes.key?(:'encryption_algorithm')
self.encryption_algorithm = attributes[:'encryption_algorithm'] if attributes[:'encryption_algorithm']
self.diffie_helman_group = attributes[:'diffieHelmanGroup'] if attributes[:'diffieHelmanGroup']
raise 'You cannot provide both :diffieHelmanGroup and :diffie_helman_group' if attributes.key?(:'diffieHelmanGroup') && attributes.key?(:'diffie_helman_group')
self.diffie_helman_group = attributes[:'diffie_helman_group'] if attributes[:'diffie_helman_group']
self.lifetime_in_seconds = attributes[:'lifetimeInSeconds'] if attributes[:'lifetimeInSeconds']
raise 'You cannot provide both :lifetimeInSeconds and :lifetime_in_seconds' if attributes.key?(:'lifetimeInSeconds') && attributes.key?(:'lifetime_in_seconds')
self.lifetime_in_seconds = attributes[:'lifetime_in_seconds'] if attributes[:'lifetime_in_seconds']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Custom attribute writer method checking allowed values (enum).
# @param [Object] authentication_algorithm Object to be assigned
def authentication_algorithm=(authentication_algorithm)
raise "Invalid value for 'authentication_algorithm': this must be one of the values in AUTHENTICATION_ALGORITHM_ENUM." if authentication_algorithm && !AUTHENTICATION_ALGORITHM_ENUM.include?(authentication_algorithm)
@authentication_algorithm = authentication_algorithm
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] encryption_algorithm Object to be assigned
def encryption_algorithm=(encryption_algorithm)
raise "Invalid value for 'encryption_algorithm': this must be one of the values in ENCRYPTION_ALGORITHM_ENUM." if encryption_algorithm && !ENCRYPTION_ALGORITHM_ENUM.include?(encryption_algorithm)
@encryption_algorithm = encryption_algorithm
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] diffie_helman_group Object to be assigned
def diffie_helman_group=(diffie_helman_group)
raise "Invalid value for 'diffie_helman_group': this must be one of the values in DIFFIE_HELMAN_GROUP_ENUM." if diffie_helman_group && !DIFFIE_HELMAN_GROUP_ENUM.include?(diffie_helman_group)
@diffie_helman_group = diffie_helman_group
end
# 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 &&
is_custom_phase_one_config == other.is_custom_phase_one_config &&
authentication_algorithm == other.authentication_algorithm &&
encryption_algorithm == other.encryption_algorithm &&
diffie_helman_group == other.diffie_helman_group &&
lifetime_in_seconds == other.lifetime_in_seconds
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
[is_custom_phase_one_config, authentication_algorithm, encryption_algorithm, diffie_helman_group, lifetime_in_seconds].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
| 43.416988 | 245 | 0.725389 |
4a2b671da1ae86cb2f95eda33d01f176cd076580 | 1,946 |
require 'open3'
module OFlow
module Actors
#
class ShellOne < Actor
attr_reader :dir
attr_reader :cmd
attr_reader :timeout
def initialize(task, options)
super
@dir = options[:dir]
@dir = '.' if @dir.nil?
@dir = File.expand_path(@dir.strip)
@cmd = options[:cmd]
@timeout = options.fetch(:timeout, 1.0).to_f
@timeout = 0.001 if 0.001 > @timeout
end
def perform(op, box)
input = Oj.dump(box.contents, mode: :compat, indent: 0)
i, o, e, _ = Open3.popen3(@cmd, chdir: @dir)
i.write(input)
i.close
giveup = Time.now + @timeout
ra = [e, o]
out = ''
err = ''
ec = false # stderr closed flag
oc = false # stdout closed flag
while true
rem = giveup - Time.now
raise Exception.new("Timed out waiting for output.") if 0.0 > rem
rs, _, es = select(ra, nil, ra, rem)
unless es.nil?
es.each do |io|
ec |= io == e
oc |= io == o
end
end
break if ec && oc
unless rs.nil?
rs.each do |io|
if io == e && !ec
if io.closed? || io.eof?
ec = true
next
end
err += io.read_nonblock(1000)
elsif io == o && !oc
if io.closed? || io.eof?
oc = true
next
end
out += io.read_nonblock(1000)
end
end
end
break if ec && oc
end
if 0 < err.length
raise Exception.new(err)
end
output = Oj.load(out, mode: :compat)
o.close
e.close
task.ship(nil, Box.new(output, box.tracker))
end
end # ShellOne
end # Actors
end # OFlow
| 24.325 | 75 | 0.44296 |
010f6f19cdc45b3082e063f359c8d0e9e7958d31 | 14,820 | require 'rails_helper'
require 'sunspot/rails/spec_helper'
describe ClassificationTypesController do
fixtures :all
disconnect_sunspot
def valid_attributes
FactoryBot.attributes_for(:classification_type)
end
describe 'GET index' do
before(:each) do
FactoryBot.create(:classification_type)
end
describe 'When logged in as Administrator' do
login_admin
it 'assigns all classification_types as @classification_types' do
get :index
expect(assigns(:classification_types)).to eq(ClassificationType.order(:position))
end
end
describe 'When logged in as Librarian' do
login_librarian
it 'assigns all classification_types as @classification_types' do
get :index
expect(assigns(:classification_types)).to eq(ClassificationType.order(:position))
end
end
describe 'When logged in as User' do
login_user
it 'assigns all classification_types as @classification_types' do
get :index
expect(assigns(:classification_types)).to eq(ClassificationType.order(:position))
end
end
describe 'When not logged in' do
it 'assigns all classification_types as @classification_types' do
get :index
expect(assigns(:classification_types)).to eq(ClassificationType.order(:position))
end
end
end
describe 'GET show' do
describe 'When logged in as Administrator' do
login_admin
it 'assigns the requested classification_type as @classification_type' do
classification_type = FactoryBot.create(:classification_type)
get :show, params: { id: classification_type.id }
expect(assigns(:classification_type)).to eq(classification_type)
end
end
describe 'When logged in as Librarian' do
login_librarian
it 'assigns the requested classification_type as @classification_type' do
classification_type = FactoryBot.create(:classification_type)
get :show, params: { id: classification_type.id }
expect(assigns(:classification_type)).to eq(classification_type)
end
end
describe 'When logged in as User' do
login_user
it 'assigns the requested classification_type as @classification_type' do
classification_type = FactoryBot.create(:classification_type)
get :show, params: { id: classification_type.id }
expect(assigns(:classification_type)).to eq(classification_type)
end
end
describe 'When not logged in' do
it 'assigns the requested classification_type as @classification_type' do
classification_type = FactoryBot.create(:classification_type)
get :show, params: { id: classification_type.id }
expect(assigns(:classification_type)).to eq(classification_type)
end
end
end
describe 'GET new' do
describe 'When logged in as Administrator' do
login_admin
it 'assigns the requested classification_type as @classification_type' do
get :new
expect(assigns(:classification_type)).not_to be_valid
expect(response).to be_successful
end
end
describe 'When logged in as Librarian' do
login_librarian
it 'should not assign the requested classification_type as @classification_type' do
get :new
expect(assigns(:classification_type)).to be_nil
expect(response).to be_forbidden
end
end
describe 'When logged in as User' do
login_user
it 'should not assign the requested classification_type as @classification_type' do
get :new
expect(assigns(:classification_type)).to be_nil
expect(response).to be_forbidden
end
end
describe 'When not logged in' do
it 'should not assign the requested classification_type as @classification_type' do
get :new
expect(assigns(:classification_type)).to be_nil
expect(response).to redirect_to(new_user_session_url)
end
end
end
describe 'GET edit' do
describe 'When logged in as Administrator' do
login_admin
it 'assigns the requested classification_type as @classification_type' do
classification_type = FactoryBot.create(:classification_type)
get :edit, params: { id: classification_type.id }
expect(assigns(:classification_type)).to eq(classification_type)
end
end
describe 'When logged in as Librarian' do
login_librarian
it 'assigns the requested classification_type as @classification_type' do
classification_type = FactoryBot.create(:classification_type)
get :edit, params: { id: classification_type.id }
expect(response).to be_forbidden
end
end
describe 'When logged in as User' do
login_user
it 'assigns the requested classification_type as @classification_type' do
classification_type = FactoryBot.create(:classification_type)
get :edit, params: { id: classification_type.id }
expect(response).to be_forbidden
end
end
describe 'When not logged in' do
it 'should not assign the requested classification_type as @classification_type' do
classification_type = FactoryBot.create(:classification_type)
get :edit, params: { id: classification_type.id }
expect(response).to redirect_to(new_user_session_url)
end
end
end
describe 'POST create' do
before(:each) do
@attrs = valid_attributes
@invalid_attrs = { name: '' }
end
describe 'When logged in as Administrator' do
login_admin
describe 'with valid params' do
it 'assigns a newly created classification_type as @classification_type' do
post :create, params: { classification_type: @attrs }
expect(assigns(:classification_type)).to be_valid
end
it 'redirects to the created agent' do
post :create, params: { classification_type: @attrs }
expect(response).to redirect_to(assigns(:classification_type))
end
end
describe 'with invalid params' do
it 'assigns a newly created but unsaved classification_type as @classification_type' do
post :create, params: { classification_type: @invalid_attrs }
expect(assigns(:classification_type)).not_to be_valid
end
it 'should be successful' do
post :create, params: { classification_type: @invalid_attrs }
expect(response).to be_successful
end
end
end
describe 'When logged in as Librarian' do
login_librarian
describe 'with valid params' do
it 'assigns a newly created classification_type as @classification_type' do
post :create, params: { classification_type: @attrs }
expect(assigns(:classification_type)).to be_nil
end
it 'should be forbidden' do
post :create, params: { classification_type: @attrs }
expect(response).to be_forbidden
end
end
describe 'with invalid params' do
it 'assigns a newly created but unsaved classification_type as @classification_type' do
post :create, params: { classification_type: @invalid_attrs }
expect(assigns(:classification_type)).to be_nil
end
it 'should be forbidden' do
post :create, params: { classification_type: @invalid_attrs }
expect(response).to be_forbidden
end
end
end
describe 'When logged in as User' do
login_user
describe 'with valid params' do
it 'assigns a newly created classification_type as @classification_type' do
post :create, params: { classification_type: @attrs }
expect(assigns(:classification_type)).to be_nil
end
it 'should be forbidden' do
post :create, params: { classification_type: @attrs }
expect(response).to be_forbidden
end
end
describe 'with invalid params' do
it 'assigns a newly created but unsaved classification_type as @classification_type' do
post :create, params: { classification_type: @invalid_attrs }
expect(assigns(:classification_type)).to be_nil
end
it 'should be forbidden' do
post :create, params: { classification_type: @invalid_attrs }
expect(response).to be_forbidden
end
end
end
describe 'When not logged in' do
describe 'with valid params' do
it 'assigns a newly created classification_type as @classification_type' do
post :create, params: { classification_type: @attrs }
expect(assigns(:classification_type)).to be_nil
end
it 'should be forbidden' do
post :create, params: { classification_type: @attrs }
expect(response).to redirect_to(new_user_session_url)
end
end
describe 'with invalid params' do
it 'assigns a newly created but unsaved classification_type as @classification_type' do
post :create, params: { classification_type: @invalid_attrs }
expect(assigns(:classification_type)).to be_nil
end
it 'should be forbidden' do
post :create, params: { classification_type: @invalid_attrs }
expect(response).to redirect_to(new_user_session_url)
end
end
end
end
describe 'PUT update' do
before(:each) do
@classification_type = FactoryBot.create(:classification_type)
@attrs = valid_attributes
@invalid_attrs = { name: '' }
end
describe 'When logged in as Administrator' do
login_admin
describe 'with valid params' do
it 'updates the requested classification_type' do
put :update, params: { id: @classification_type.id, classification_type: @attrs }
end
it 'assigns the requested classification_type as @classification_type' do
put :update, params: { id: @classification_type.id, classification_type: @attrs }
expect(assigns(:classification_type)).to eq(@classification_type)
end
it 'moves its position when specified' do
put :update, params: { id: @classification_type.id, classification_type: @attrs, move: 'lower' }
expect(response).to redirect_to(classification_types_url)
end
end
describe 'with invalid params' do
it 'assigns the requested classification_type as @classification_type' do
put :update, params: { id: @classification_type.id, classification_type: @invalid_attrs }
expect(response).to render_template('edit')
end
end
end
describe 'When logged in as Librarian' do
login_librarian
describe 'with valid params' do
it 'updates the requested classification_type' do
put :update, params: { id: @classification_type.id, classification_type: @attrs }
end
it 'assigns the requested classification_type as @classification_type' do
put :update, params: { id: @classification_type.id, classification_type: @attrs }
expect(assigns(:classification_type)).to eq(@classification_type)
expect(response).to be_forbidden
end
end
describe 'with invalid params' do
it 'assigns the requested classification_type as @classification_type' do
put :update, params: { id: @classification_type.id, classification_type: @invalid_attrs }
expect(response).to be_forbidden
end
end
end
describe 'When logged in as User' do
login_user
describe 'with valid params' do
it 'updates the requested classification_type' do
put :update, params: { id: @classification_type.id, classification_type: @attrs }
end
it 'assigns the requested classification_type as @classification_type' do
put :update, params: { id: @classification_type.id, classification_type: @attrs }
expect(assigns(:classification_type)).to eq(@classification_type)
expect(response).to be_forbidden
end
end
describe 'with invalid params' do
it 'assigns the requested classification_type as @classification_type' do
put :update, params: { id: @classification_type.id, classification_type: @invalid_attrs }
expect(response).to be_forbidden
end
end
end
describe 'When not logged in' do
describe 'with valid params' do
it 'updates the requested classification_type' do
put :update, params: { id: @classification_type.id, classification_type: @attrs }
end
it 'should be forbidden' do
put :update, params: { id: @classification_type.id, classification_type: @attrs }
expect(response).to redirect_to(new_user_session_url)
end
end
describe 'with invalid params' do
it 'assigns the requested classification_type as @classification_type' do
put :update, params: { id: @classification_type.id, classification_type: @invalid_attrs }
expect(response).to redirect_to(new_user_session_url)
end
end
end
end
describe 'DELETE destroy' do
before(:each) do
@classification_type = FactoryBot.create(:classification_type)
end
describe 'When logged in as Administrator' do
login_admin
it 'destroys the requested classification_type' do
delete :destroy, params: { id: @classification_type.id }
end
it 'redirects to the classification_types list' do
delete :destroy, params: { id: @classification_type.id }
expect(response).to redirect_to(classification_types_url)
end
end
describe 'When logged in as Librarian' do
login_librarian
it 'destroys the requested classification_type' do
delete :destroy, params: { id: @classification_type.id }
end
it 'should be forbidden' do
delete :destroy, params: { id: @classification_type.id }
expect(response).to be_forbidden
end
end
describe 'When logged in as User' do
login_user
it 'destroys the requested classification_type' do
delete :destroy, params: { id: @classification_type.id }
end
it 'should be forbidden' do
delete :destroy, params: { id: @classification_type.id }
expect(response).to be_forbidden
end
end
describe 'When not logged in' do
it 'destroys the requested classification_type' do
delete :destroy, params: { id: @classification_type.id }
end
it 'should be forbidden' do
delete :destroy, params: { id: @classification_type.id }
expect(response).to redirect_to(new_user_session_url)
end
end
end
end
| 33.2287 | 106 | 0.671727 |
ab4c7cb5f4d144101f867241ba8ad350e0a336e6 | 157 | json.array!(@users) do |user|
json.extract! user, :id, :state, :name, :description, :email, :username, :roles
json.url user_url(user, format: :json)
end
| 31.4 | 81 | 0.681529 |
87e1c11ce195287879614b03aa173a41d80cf3bb | 1,056 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe GitlabSchema.types['ContainerRepository'] do
fields = %i[id name path location created_at updated_at expiration_policy_started_at status tags_count can_delete expiration_policy_cleanup_status project]
it { expect(described_class.graphql_name).to eq('ContainerRepository') }
it { expect(described_class.description).to eq('A container repository') }
it { expect(described_class).to require_graphql_authorizations(:read_container_image) }
it { expect(described_class).to have_graphql_fields(fields) }
describe 'status field' do
subject { described_class.fields['status'] }
it 'returns status enum' do
is_expected.to have_graphql_type(Types::ContainerRepositoryStatusEnum)
end
end
describe 'expiration_policy_cleanup_status field' do
subject { described_class.fields['expirationPolicyCleanupStatus'] }
it 'returns cleanup status enum' do
is_expected.to have_graphql_type(Types::ContainerRepositoryCleanupStatusEnum)
end
end
end
| 33 | 157 | 0.786932 |
879a6e6b7546fb40b8050fb474b7dca5824c76e2 | 610 | # frozen_string_literal: true
module Schemas
module Static
class Generate
module NGLP
# @api private
class Journal < Schemas::Static::Generator
def generate
set! "publisher.name", Faker::Book.publisher
set! "publisher.email", Faker::Internet.safe_email, skip_chance: 50
set! "publisher.collaborators", Contributor.sample(3)
set! :collected_on, Faker::Date.backward
set_random_option! "grouping.category"
set! "grouping.tags", random_colors
end
end
end
end
end
end
| 22.592593 | 79 | 0.604918 |
0375e4ba9d6260ae9cacf156892279aa116fc726 | 998 | describe PipelineService::V2::Nouns::User do
include_context "stubbed_network"
subject { described_class.new(object: noun) }
let(:active_record_object) { ::User.create }
let!(:pseudonym) { ::Pseudonym.create(user_id: active_record_object.id, sis_user_id: '1234') }
let(:noun) { PipelineService::V2::Noun.new(active_record_object)}
describe '#call'do
it 'returns with sis_user_id' do
expect(subject.call).to include({'sis_user_id' => '1234'})
end
context "with partner name" do
it 'returns with a partner name' do
allow(SettingsService).to receive(:get_settings).and_return('partner_name' => 'testschool')
expect(subject.call).to include({'partner_name' => 'testschool'})
end
end
context "without partner name" do
it 'returns with a partner name' do
allow(SettingsService).to receive(:get_settings).and_return({})
expect(subject.call).to include({'partner_name' => nil})
end
end
end
end
| 30.242424 | 99 | 0.677355 |
38d0bfce96154cd8e4767c0214e56913377d58e1 | 2,854 | #
# Author:: Adam Jacob (<[email protected]>)
# Author:: Tyler Cloke (<[email protected]>)
# Copyright:: Copyright 2008-2017, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "spec_helper"
describe Chef::Resource::Package do
let(:resource) { Chef::Resource::Package.new("emacs") }
it "sets the package_name to the first argument to new" do
expect(resource.package_name).to eql("emacs")
end
it "accepts a string for the package name" do
resource.package_name "something"
expect(resource.package_name).to eql("something")
end
it "accepts a string for the version" do
resource.version "something"
expect(resource.version).to eql("something")
end
it "accepts a string for the response file" do
resource.response_file "something"
expect(resource.response_file).to eql("something")
end
it "accepts a hash for response file template variables" do
resource.response_file_variables({ :variables => true })
expect(resource.response_file_variables).to eql({ :variables => true })
end
it "accepts a string for the source" do
resource.source "something"
expect(resource.source).to eql("something")
end
it "accepts a string for the options" do
resource.options "something"
expect(resource.options).to eql(["something"])
end
it "splits options" do
resource.options "-a -b 'arg with spaces' -b \"and quotes\""
expect(resource.options).to eql(["-a", "-b", "arg with spaces", "-b", "and quotes"])
end
describe "when it has a package_name and version" do
before do
resource.package_name("tomcat")
resource.version("10.9.8")
resource.options("-al")
end
it "describes its state" do
state = resource.state_for_resource_reporter
expect(state[:version]).to eq("10.9.8")
expect(state[:options]).to eq(["-al"])
end
it "returns the file path as its identity" do
expect(resource.identity).to eq("tomcat")
end
it "takes options as an array" do
resource.options [ "-a", "-l" ]
expect(resource.options).to eq(["-a", "-l" ])
end
end
# String, Integer
[ "600", 600 ].each do |val|
it "supports setting a timeout as a #{val.class}" do
resource.timeout(val)
expect(resource.timeout).to eql(val)
end
end
end
| 30.042105 | 88 | 0.686055 |
269410bc04de07867beee3bb94e15b29bfc9bc0d | 1,848 | class Atomicparsley < Formula
desc "MPEG-4 command-line tool"
homepage "https://bitbucket.org/wez/atomicparsley/overview/"
url "https://bitbucket.org/wez/atomicparsley/get/0.9.6.tar.bz2"
sha256 "e28d46728be86219e6ce48695ea637d831ca0170ca6bdac99810996a8291ee50"
revision 1
head "https://bitbucket.org/wez/atomicparsley", :using => :hg
bottle do
cellar :any_skip_relocation
sha256 "632b3bc281a6f3bd5b9a913dff1e805c9fb9997f41b4a02db0a1aa34f6faced3" => :catalina
sha256 "d32a565f675bd0b2c5ebf1b5aee01fb79d9d42b072dedf724b7ee03b2cc242ee" => :mojave
sha256 "05c4cdc1dfc14fa6f06fdbbcadead5055a9fb53091d014458b86ecb4b22111fe" => :high_sierra
sha256 "d5f8672d420511ff76fd9ecc4d41c8aee5eecbf4382d7c4bd3fb04400c4617f4" => :sierra
sha256 "c0a7964ced998b2db7150f95b9329e138f28f0768be50d531fd4d82754e0ebde" => :el_capitan
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
uses_from_macos "zlib"
# Fix Xcode 9 pointer warnings
# https://bitbucket.org/wez/atomicparsley/issues/52/xcode-9-build-failure
if DevelopmentTools.clang_build_version >= 900
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/ac8624c36e/atomicparsley/xcode9.patch"
sha256 "15b87be1800760920ac696a93131cab1c0f35ce4c400697bb8b0648765767e5f"
end
end
def install
system "./autogen.sh"
system "./configure", "--prefix=#{prefix}",
"--disable-debug",
"--disable-universal"
system "make", "install"
end
test do
cp test_fixtures("test.m4a"), testpath/"file.m4a"
system "#{bin}/AtomicParsley", testpath/"file.m4a", "--artist", "Homebrew", "--overWrite"
output = shell_output("#{bin}/AtomicParsley file.m4a --textdata")
assert_match "Homebrew", output
end
end
| 38.5 | 108 | 0.735931 |
1dea0f6ef45ab7c17387094c4b5c06f092300a05 | 1,767 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'departure/version'
# This environment variable is set on CI to facilitate testing with multiple
# versions of Rails.
RAILS_DEPENDENCY_VERSION = ENV.fetch('RAILS_VERSION', ['>= 5.2.0', '< 6.1'])
Gem::Specification.new do |spec|
spec.name = 'departure'
spec.version = Departure::VERSION
spec.authors = ['Ilya Zayats', 'Pau Pérez', 'Fran Casas', 'Jorge Morante', 'Enrico Stano', 'Adrian Serafin', 'Kirk Haines', 'Guillermo Iguaran']
spec.email = ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']
spec.summary = %q(pt-online-schema-change runner for ActiveRecord migrations)
spec.description = %q(Execute your ActiveRecord migrations with Percona's pt-online-schema-change. Formerly known as Percona Migrator.)
spec.homepage = 'https://github.com/departurerb/departure'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.require_paths = ['lib']
spec.add_runtime_dependency 'railties', *Array(RAILS_DEPENDENCY_VERSION)
spec.add_runtime_dependency 'activerecord', *Array(RAILS_DEPENDENCY_VERSION)
spec.add_runtime_dependency 'mysql2', '>= 0.4.0', '<= 0.5.3'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.4', '>= 3.4.0'
spec.add_development_dependency 'rspec-its', '~> 1.2'
spec.add_development_dependency 'byebug', '~> 8.2', '>= 8.2.1'
spec.add_development_dependency 'climate_control', '~> 0.0.3'
end
| 49.083333 | 198 | 0.696095 |
f7e690aef264ba76ce9fa034392e554dafbb40d8 | 517 | class FeedPresenter < BasePresenter
presents :feed
def feed_link(&block)
args = [
@template.feed_entries_path(feed),
remote: true,
class: "feed-link",
data: {
behavior: "selectable show_entries open_item feed_link renamable user_title",
feed_id: feed.id,
mark_read: {
type: "feed",
data: feed.id,
message: "Mark #{feed.title} as read?"
}.to_json
}
]
@template.link_to *args do
yield
end
end
end
| 20.68 | 85 | 0.5706 |
112b6299f95c93749d6082fa44e038e28da83ad2 | 2,866 | require "simphi/request"
require "spec_helper"
describe Simphi::Request do
context "#normalize_hash_params" do
let(:request) { Simphi::Request.new(double) }
before do
allow_any_instance_of(Simphi::Request).to receive(:POST).and_return(params_before)
allow_any_instance_of(Simphi::Request).to receive(:GET).and_return({})
end
context "when params not include hash" do
let(:params_before) do
{
"five" => "five",
"one" => {
"two" => "two",
"three" => "three"
},
"four" => "four"
}
end
it "not change the hash" do
request.normalize_hash_params
expect(request.params).to eq params_before
end
end
context "when params include well formed hashes" do
let(:params_before) do
{
"one" => "one",
"two" => {
"more" => {
"first-simphi" => {
"first-pair" => {
"key" => "first-key",
"value" => "first-value"
},
"second" => {
"key" => "second-key",
"value" => "second-value"
}
}
}
},
"three-simphi" => {
"first-pair" => {
"key" => "first-key",
"value" => "first-value"
}
}
}
end
let(:params_after) do
{
"one" => "one",
"two" => {
"more" => {
"first" => {
"first-key" => "first-value",
"second-key" => "second-value"
}
}
},
"three" => {
"first-key" => "first-value"
}
}
end
it "change the hash" do
request.normalize_hash_params
expect(request.params).to eq params_after
end
end
context "when include not formed properly hash param because of" do
context "include only key" do
let(:params_before) do
{
"first-simphi" => {
"first-pair" => {
"key" => "first-key"
}
}
}
end
it "should raise exception" do
expect { request.normalize_hash_params }.to raise_error(ArgumentError)
end
end
context "include key and value but with incorect names" do
let(:params_before) do
{
"first-simphi" => {
"first-pair" => {
"k" => "first-key",
"value" => "first-value"
}
}
}
end
it "should raise exception" do
expect { request.normalize_hash_params }.to raise_error(ArgumentError)
end
end
end
end
end
| 24.084034 | 88 | 0.43859 |
1ccba0f7680950eb7cae949d74e7a9d8d0324a44 | 576 | Pod::Spec.new do |s|
s.name = "DDNavText"
s.version = "1.1.1"
s.summary = "Easily show additional text in your UINavigationBar title."
s.homepage = "http://github.com/Dids/DDNavText"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Pauli 'Dids' Jokela" => "[email protected]" }
s.source = { :git => "https://github.com/Dids/DDNavText.git", :tag => "1.1.1" }
s.source_files = 'DDNavText/*.{h,m}'
s.platform = :ios, '8.4'
s.requires_arc = true
end
| 38.4 | 91 | 0.53125 |
62b8f0360a331471e882fdc63d334e67a973843a | 586 | require_relative '../lib/envo'
require 'test/unit'
include Envo
class TestStringVal < Test::Unit::TestCase
def test_casts
s = StringVal.new('xyz')
assert_equal s.type, :string
assert !s.list?
assert_equal s.value, 'xyz'
s.clean!
assert_equal s.value, 'xyz'
assert_same s.to_s, s.value
assert s.accept_assign?(5)
assert !s.invalid_description
l = s.to_list
assert_equal l.type, :list
assert_equal l.ar, ['xyz']
s.value = ''
assert_equal s.invalid_description, 'empty string'
s.clean!
assert_nil s.value
end
end
| 18.3125 | 54 | 0.662116 |
e97aaaebf7981e3a8f70a8dbf0ce20fd962b4d42 | 526 | # encoding: UTF-8
require 'spec_helper'
describe NanoApi::Model do
let(:model) do
Class.new do
include NanoApi::Model
attribute :name
attribute :count, default: 0
end
end
specify{model.i18n_scope.should == :nano_model}
specify{model.new.should_not be_persisted}
specify{model.instantiate({}).should be_an_instance_of model}
specify{model.instantiate({}).should be_persisted}
context 'Fault tolerance' do
specify{ expect{ model.new(:foo => 'bar') }.not_to raise_error}
end
end | 22.869565 | 67 | 0.707224 |
380d55b7a52d68cdce2de17fc9e6eedb6ce24375 | 325 | module Ricer4::Plugins::Hash
class Hash < Ricer4::Plugin
trigger_is "hash.algo"
has_usage '<string|named:"hash">'
def execute(hash)
end
has_usage '<hash_algo> <message|named:"plaintext">', function: :execute_with_algo
def execute_with_algo(algo, hash)
end
end
end | 19.117647 | 85 | 0.627692 |
ed8d53ab510543de9172a311a8696cf292842261 | 583 | require 'wargaming_api/world_of_tanks/authentication'
module WargamingApi
class WargamingApi::WorldOfTanks::Authentication
class WargamingApi::WorldOfTanks::Authentication::OpenIDLogin < WargamingApi::WorldOfTanks::Authentication
attr_accessor :expires_at, :redirect_uri, :display, :nofollow
def initialize
@language = 'en'
@account_id = 509851940
@application_id = WargamingApi::APP_TOKEN
@link = 'api.worldoftanks.eu/wot/auth/login'
end
puts 'WorldOfTanks => Authentication -> OpenIDLogin loaded.'
end
end
end | 30.684211 | 110 | 0.720412 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.