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
|
---|---|---|---|---|---|
391446773fd1fe5017e0681129f1423c98b1610b | 172 | class Helpers
def self.current_user(session)
User.find(session[:user_id])
end
def self.is_logged_in?(session)
!!session[:user_id]
end
end | 17.2 | 36 | 0.633721 |
26754632cb0f10e35c67e080eaf44bd81ff8fe80 | 1,510 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::EventGrid::Mgmt::V2020_04_01_preview
module Models
#
# Properties of the PartnerNamespace update.
#
class PartnerNamespaceUpdateParameters
include MsRestAzure
# @return [Hash{String => String}] Tags of the partner namespace.
attr_accessor :tags
#
# Mapper for PartnerNamespaceUpdateParameters class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'PartnerNamespaceUpdateParameters',
type: {
name: 'Composite',
class_name: 'PartnerNamespaceUpdateParameters',
model_properties: {
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
}
}
}
}
end
end
end
end
| 27.454545 | 71 | 0.525166 |
185576800652ef4f4d7ea1a93394d738334d02d2 | 449 | # Logging configuration for the whole app.
#
# For details see https://github.com/TwP/logging
require 'logging'
require 'rack-timeout'
Logging.logger.root.tap do |root|
root.appenders = Logging.appenders.stdout(
layout: Logging::Layouts.pattern(format_as: :inspect, pattern: '%-5l [%c]: %m\n')
)
root.level = (Config.rack_env == 'development' ? :debug : :info)
end
if Config.timeout > 0
Rack::Timeout::Logger.level = Logger::WARN
end
| 24.944444 | 85 | 0.703786 |
38ed3dbac8e317aaad3a1e4a447f50048e6a7f9e | 1,131 | # frozen_string_literal: true
module Spree
module Admin
class CollaboratorsController < Spree::Admin::ResourceController
def index
@collaborators = collection
end
def edit
@collaborator = Spree::Collaborator.find(params[:id])
authorize! :update, @collaborator
end
def update
@collaborator = Spree::Collaborator.find(params[:id])
authorize! :update, @collaborator
if @collaborator.update(collabs_params)
flash[:notice] = I18n.t('spree.purchase_policy_successfully_submitted')
redirect_to spree.collaborator_path(@collaborator)
else
render :edit
end
end
private
def permitted_collabs_attributes
%i[name address phone_number email sex]
end
def collabs_params
params.require(:collaborator).permit(permitted_collabs_attributes)
end
def collection
params[:q] ||= {}
@search = Spree::Collaborator.ransack(params[:q])
@collection = @search.result.page(params[:page]).per(params[:per_page])
end
end
end
end
| 24.586957 | 81 | 0.640141 |
ab270dbdd382c6f513f8888674c50f53ccd06924 | 109 | require_relative 'graph'
require_relative 'priority_map'
# O(|V| + |E|*log(|V|)).
def dijkstra2(source)
end
| 15.571429 | 31 | 0.706422 |
b9129045347868f3a252193a8758b498af80db55 | 10,402 | #--
# Author:: Daniel DeLeo (<[email protected]>)
# Copyright:: Copyright (c) 2012 Opscode, 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.
#
class Chef
class Node
# == AttrArray
# AttrArray is identical to Array, except that it keeps a reference to the
# "root" (Chef::Node::Attribute) object, and will trigger a cache
# invalidation on that object when mutated.
class AttrArray < Array
MUTATOR_METHODS = [
:<<,
:[]=,
:clear,
:collect!,
:compact!,
:default=,
:default_proc=,
:delete,
:delete_at,
:delete_if,
:fill,
:flatten!,
:insert,
:keep_if,
:map!,
:merge!,
:pop,
:push,
:update,
:reject!,
:reverse!,
:replace,
:select!,
:shift,
:slice!,
:sort!,
:sort_by!,
:uniq!,
:unshift
]
# For all of the methods that may mutate an Array, we override them to
# also invalidate the cached merged_attributes on the root
# Node::Attribute object.
MUTATOR_METHODS.each do |mutator|
define_method(mutator) do |*args, &block|
root.reset_cache(root.top_level_breadcrumb)
super(*args, &block)
end
end
attr_reader :root
def initialize(root, data)
@root = root
super(data)
end
# For elements like Fixnums, true, nil...
def safe_dup(e)
e.dup
rescue TypeError
e
end
def dup
Array.new(map {|e| safe_dup(e)})
end
end
# == VividMash
# VividMash is identical to a Mash, with a few exceptions:
# * It has a reference to the root Chef::Node::Attribute to which it
# belongs, and will trigger cache invalidation on that object when
# mutated.
# * It auto-vivifies, that is a reference to a missing element will result
# in the creation of a new VividMash for that key. (This only works when
# using the element reference method, `[]` -- other methods, such as
# #fetch, work as normal).
# * It supports a set_unless flag (via the root Attribute object) which
# allows `||=` style behavior (`||=` does not work with
# auto-vivification). This is only implemented for #[]=; methods such as
# #store work as normal.
# * attr_accessor style element set and get are supported via method_missing
class VividMash < Mash
attr_reader :root
# Methods that mutate a VividMash. Each of them is overridden so that it
# also invalidates the cached merged_attributes on the root Attribute
# object.
MUTATOR_METHODS = [
:clear,
:delete,
:delete_if,
:keep_if,
:merge!,
:update,
:reject!,
:replace,
:select!,
:shift
]
# For all of the mutating methods on Mash, override them so that they
# also invalidate the cached `merged_attributes` on the root Attribute
# object.
MUTATOR_METHODS.each do |mutator|
define_method(mutator) do |*args, &block|
root.reset_cache(root.top_level_breadcrumb)
super(*args, &block)
end
end
def initialize(root, data={})
@root = root
super(data)
end
def [](key)
root.top_level_breadcrumb ||= key
value = super
if !key?(key)
value = self.class.new(root)
self[key] = value
else
value
end
end
def []=(key, value)
root.top_level_breadcrumb ||= key
if set_unless? && key?(key)
self[key]
else
root.reset_cache(root.top_level_breadcrumb)
super
end
end
alias :attribute? :has_key?
def method_missing(symbol, *args)
# Calling `puts arg` implicitly calls #to_ary on `arg`. If `arg` does
# not implement #to_ary, ruby recognizes it as a single argument, and
# if it returns an Array, then ruby prints each element. If we don't
# account for that here, we'll auto-vivify a VividMash for the key
# :to_ary which creates an unwanted key and raises a TypeError.
if symbol == :to_ary
super
elsif args.empty?
self[symbol]
elsif symbol.to_s =~ /=$/
key_to_set = symbol.to_s[/^(.+)=$/, 1]
self[key_to_set] = (args.length == 1 ? args[0] : args)
else
raise NoMethodError, "Undefined node attribute or method `#{symbol}' on `node'. To set an attribute, use `#{symbol}=value' instead."
end
end
def set_unless?
@root.set_unless?
end
def convert_key(key)
super
end
# Mash uses #convert_value to mashify values on input.
# We override it here to convert hash or array values to VividMash or
# AttrArray for consistency and to ensure that the added parts of the
# attribute tree will have the correct cache invalidation behavior.
def convert_value(value)
case value
when VividMash
value
when Hash
VividMash.new(root, value)
when Array
AttrArray.new(root, value)
else
value
end
end
def dup
Mash.new(self)
end
end
# == MultiMash
# This is a Hash-like object that contains multiple VividMashes in it. Its
# purpose is so that the user can descend into the mash and delete a subtree
# from all of the Mash objects (used to delete all values in a subtree from
# default, force_default, role_default and env_default at the same time). The
# assignment operator strictly does assignment (does no merging) and works
# by deleting the subtree and then assigning to the last mash which passed in
# the initializer.
#
# A lot of the complexity of this class comes from the fact that at any key
# value some or all of the mashes may walk off their ends and become nil or
# true or something. The schema may change so that one precidence leve may
# be 'true' object and another may be a VividMash. It is also possible that
# one or many of them may transition from VividMashes to Hashes or Arrays.
#
# It also supports the case where you may be deleting a key using node.rm
# in which case if intermediate keys all walk off into nil then you don't want
# to be autovivifying keys as you go. On the other hand you may be using
# node.force_default! in which case you'll wind up with a []= operator at the
# end and you want autovivification, so we conditionally have to support either
# operation.
#
# @todo: can we have an autovivify class that decorates a class that doesn't
# autovivify or something so that the code is less awful?
#
class MultiMash
attr_reader :root
attr_reader :mashes
attr_reader :opts
attr_reader :primary_mash
# Initialize with an array of mashes. For the delete return value to work
# properly the mashes must come from the same attribute level (i.e. all
# override or all default, but not a mix of both).
def initialize(root, primary_mash, mashes, opts={})
@root = root
@primary_mash = primary_mash
@mashes = mashes
@opts = opts
@opts[:autovivify] = true if @opts[:autovivify].nil?
end
def [](key)
# handle the secondary mashes
new_mashes = []
mashes.each do |mash|
new_mash = safe_evalute_key(mash, key)
# secondary mashes never autovivify so once they fall into nil, we just stop tracking them
new_mashes.push(new_mash) unless new_mash.nil?
end
new_primary_mash = safe_evalute_key(primary_mash, key)
if new_primary_mash.nil? && @opts[:autovivify]
primary_mash[key] = VividMash.new(root)
new_primary_mash = primary_mash[key]
end
MultiMash.new(root, new_primary_mash, new_mashes, opts)
end
def []=(key, value)
if primary_mash.nil?
# This theoretically should never happen since node#force_default! setter methods will autovivify and
# node#rm methods do not end in #[]= operators.
raise TypeError, "No autovivification was specified initially on a method chain ending in assignment"
end
ret = delete(key)
primary_mash[key] = value
ret
end
# mash.element('foo', 'bar') is the same as mash['foo']['bar']
def element(key = nil, *subkeys)
return self if key.nil?
submash = self[key]
subkeys.empty? ? submash : submash.element(*subkeys)
end
def delete(key)
# the return value is a deep merge which is correct semantics when
# merging between attributes on the same level (this would be incorrect
# if passed both override and default attributes which would need hash_only
# merging).
ret = mashes.inject(Mash.new) do |merged, mash|
Chef::Mixin::DeepMerge.merge(merged, mash)
end
ret = Chef::Mixin::DeepMerge.merge(ret, primary_mash)
mashes.each do |mash|
mash.delete(key) if mash.respond_to?(:delete)
end
primary_mash.delete(key) if primary_mash.respond_to?(:delete)
ret[key]
end
private
def safe_evalute_key(mash, key)
if mash.respond_to?(:[])
if mash.respond_to?(:has_key?)
if mash.has_key?(key)
return mash[key] if mash[key].respond_to?(:[])
end
elsif !mash[key].nil?
return mash[key] if mash[key].respond_to?(:[])
end
end
return nil
end
end
end
end
| 32.104938 | 142 | 0.611325 |
ed7b7ac25646ab9ad566e2e4a0869e9f7a278cbb | 282 | FactoryBot.define do
factory :customer do
first_name "Ed"
last_name "Gruberman"
phone { rand(10 ** 10).to_s.rjust(10,'0') }
email { |u| "#{u.first_name[0]}#{u.last_name}#{(1..99).to_a.sample}@example.com".downcase }
association :user
active true
end
end
| 25.636364 | 95 | 0.638298 |
8764d9c890e99edcab4b86b4b0ebf3ad4e768f88 | 5,811 | # frozen_string_literal: true
require 'ndr_import'
require 'ndr_import/universal_importer_helper'
require 'parquet'
require 'pathname'
require_relative 'ndr_parquet_generator/version'
# Reads file using NdrImport ETL logic and creates parquet file(s)
class NdrParquetGenerator
include NdrImport::UniversalImporterHelper
attr_reader :output_files
def self.root
::File.expand_path('..', __dir__)
end
def initialize(filename, table_mappings, output_path = '')
@filename = filename
@table_mappings = YAML.load_file table_mappings
@output_path = Pathname.new(output_path)
ensure_all_mappings_are_tables
end
def load
record_count = 0
@output_files = []
extract(@filename).each do |table, rows|
arrow_fields = arrow_field_types(table)
rawtext_column_names = rawtext_names(table)
output_rows = {}
rawtext_rows = {}
table.transform(rows).each_slice(50) do |records|
records.each do |(instance, fields, _index)|
klass = instance.split('#').first
# Convert the fields to an Arrow table "row", with appropriate casting.
# Unfortunately, Arrow can't do it implicitly.
output_rows[klass] ||= []
row = arrow_fields[klass].map do |fieldname, type|
value = fields[fieldname]
cast_to_arrow_datatype(value, type)
end
output_rows[klass] << row
rawtext_rows[klass] ||= []
rawtext_row = rawtext_column_names[klass].map do |rawtext_column_name|
fields[:rawtext][rawtext_column_name]
end
rawtext_rows[klass] << rawtext_row
end
record_count += records.count
end
basename = File.basename(@filename, File.extname(@filename))
schemas = arrow_schemas(table)
output_rows.each do |klass, records|
# Save the mapped parquet file
arrow_table = Arrow::Table.new(schemas[klass], records)
output_filename = @output_path.join("#{basename}.#{klass.underscore}.mapped.parquet")
arrow_table.save(output_filename)
@output_files << output_filename
end
rawtext_rows.each do |klass, _records|
# Save the rawtext parquet file
raw_schema = Arrow::Schema.new(rawtext_column_names[klass].map do |fieldname|
Arrow::Field.new(fieldname, :string)
end)
raw_arrow_table = Arrow::Table.new(raw_schema, rawtext_rows[klass])
output_filename = @output_path.join("#{basename}.#{klass.underscore}.raw.parquet")
raw_arrow_table.save(output_filename)
@output_files << output_filename
end
end
# puts "Inserted #{record_count} records in total"
end
private
def ensure_all_mappings_are_tables
return if @table_mappings.all? { |table| table.is_a?(NdrImport::Table) }
raise 'Mappings must be inherit from NdrImport::Table'
end
def unzip_path
@unzip_path ||= SafePath.new('unzip_path')
end
def get_notifier(_value); end
def arrow_field_types(table)
field_types = {}
masked_mappings = table.send(:masked_mappings)
masked_mappings.each do |instance, columns|
klass = instance.split('#').first
field_types[klass] ||= {}
columns.each do |column|
next if column['mappings'].nil? || column['mappings'] == []
column['mappings'].each do |mapping|
field = mapping['field']
arrow_data_type = mapping['arrow_data_type'] || :string
if arrow_data_type == :list
field_types[klass][field] = mapping.fetch('arrow_list_field').symbolize_keys
else
field_types[klass][field] = arrow_data_type
end
end
end
end
field_types
end
def arrow_schemas(table)
schemas = {}
arrow_field_types(table).each do |klass, field_type_hash|
field_array = field_type_hash.map do |fieldname, type|
if list_data_type?(type)
Arrow::Field.new(name: fieldname, type: :list, field: type.except(:split))
else
Arrow::Field.new(fieldname, type)
end
end
schemas[klass] = Arrow::Schema.new(field_array)
end
schemas
end
def rawtext_names(table)
names = {}
masked_mappings = table.send(:masked_mappings)
masked_mappings.each do |instance, columns|
klass = instance.split('#').first
names[klass] ||= []
columns.each do |column|
rawtext_column_name = column[NdrImport::Mapper::Strings::RAWTEXT_NAME] ||
column[NdrImport::Mapper::Strings::COLUMN]
next if rawtext_column_name.nil?
names[klass] << rawtext_column_name.downcase
end
end
names
end
def cast_to_arrow_datatype(value, type)
return nil if value.nil?
# puts "value: " + value.inspect
# puts "type: " + type.inspect
# puts
case type
when :int32
Integer(value)
when :boolean
ActiveRecord::Type::Boolean.new.cast(value)
when :string
value.to_s
when Hash
value.to_s.split(type[:split]) if list_data_type?(type)
else
raise "Unrecognised type: #{type.inspect}"
end
end
def list_data_type?(type)
type.is_a?(Hash) && type[:split].present?
end
end
# ActiveModel::Type::BigInteger
# ActiveModel::Type::Binary
# ActiveModel::Type::Boolean
# Type::Date
# Type::DateTime
# ActiveModel::Type::Decimal
# ActiveModel::Type::Float
# ActiveModel::Type::Integer
# ActiveModel::Type::ImmutableString
# ActiveRecord::Type::Json
# ActiveModel::Type::String
# Type::Time
# # ActiveModel::Type::Value
| 29.201005 | 93 | 0.62984 |
28ec6ad42fef49708ddd0f83def0735394106b55 | 290 | class CreateEthereumLogSubscriptions < ActiveRecord::Migration
def change
create_table :ethereum_log_subscriptions do |t|
t.integer :owner_id
t.string :owner_type
t.string :account
t.string :xid
t.datetime :end_at
t.timestamps
end
end
end
| 18.125 | 62 | 0.682759 |
9157f6c97fb4c1d441ad7d963b3ca18dbddc21f9 | 1,904 | include YARD
include Templates
module JavadocHtmlHelper
JAVA_TYPE_MATCHER = /\A(?:[a-z_$](?:[a-z0-9_$]*)\.)+[A-Z][A-Za-z_$]*/
RUBY_COLLECTION_TYPE_MATCHER = /\A(?:[A-Z][A-Za-z0-9_])(?:::[A-Z][A-Za-z0-9_]*)*</
SAXON_TYPE_MATCHER = /\A(?:net\.sf\.saxon|com\.saxonica)/
def format_types(typelist, brackets = true)
return unless typelist.is_a?(Array)
list = typelist.map { |type|
case type
when JAVA_TYPE_MATCHER
format_java_type(type)
else
super([type], false)
end
}
list.empty? ? "" : (brackets ? "(#{list.join(", ")})" : list.join(", "))
end
def format_java_type(type)
"<tt>" + linkify_saxon_type(type) + "</tt>"
end
def linkify_saxon_type(type)
case type
when SAXON_TYPE_MATCHER
link = url_for_java_object(type)
else
link = nil
end
link ? link_url(link, type, :title => h(type)) : type
end
def linkify(*args)
if args.first.is_a?(String)
case args.first
when JAVA_TYPE_MATCHER
link = url_for_java_object(args.first)
title = args.first
link ? link_url(link, title, :title => h(title)) : title
else
super
end
else
super
end
end
def url_for(obj, anchor = nil, relative = true)
case obj
when JAVA_TYPE_MATCHER
url_for_java_object(obj, anchor, relative)
else
super
end
end
def url_for_java_object(obj, anchor = nil, relative = nil)
case obj
when SAXON_TYPE_MATCHER
package, _, klass = obj.rpartition(".")
"http://saxonica.com/documentation/index.html#!javadoc/#{package}/#{klass}"
else
path = obj.split(".").join("/")
"https://docs.oracle.com/javase/8/docs/api/index.html?#{path}.html"
end
end
end
Template.extra_includes << proc { |opts| JavadocHtmlHelper if opts.format == :html }
# Engine.register_template_path(File.dirname(__FILE__)) | 26.082192 | 84 | 0.619748 |
e8afba27a5e8520078c35d3d7b4d8ce583c27b3f | 209 | class CreateAnswers < ActiveRecord::Migration[6.0]
def change
create_table :answers do |t|
t.references :question, null: false
t.text :body, null: false
t.timestamps
end
end
end
| 19 | 50 | 0.660287 |
1a28db435cd0f339e1670a0019bbdadf714e8567 | 4,565 | require 'active_record'
require 'active_support/concern'
module ActiveUUID
module Patches
module Migrations
def uuid(*column_names)
options = column_names.extract_options!
column_names.each do |name|
type = ActiveRecord::Base.connection.adapter_name.downcase == 'postgresql' ? 'uuid' : 'binary(16)'
column(name, "#{type}#{' PRIMARY KEY' if options.delete(:primary_key)}", options)
end
end
end
module Column
extend ActiveSupport::Concern
included do
def type_cast_with_uuid(value)
return UUIDTools::UUID.serialize(value) if type == :uuid
type_cast_without_uuid(value)
end
def type_cast_code_with_uuid(var_name)
return "UUIDTools::UUID.serialize(#{var_name})" if type == :uuid
type_cast_code_without_uuid(var_name)
end
def simplified_type_with_uuid(field_type)
return :uuid if field_type == 'binary(16)' || field_type == 'binary(16,0)'
simplified_type_without_uuid(field_type)
end
alias_method_chain :type_cast, :uuid
alias_method_chain :type_cast_code, :uuid if ActiveRecord::VERSION::MAJOR < 4
alias_method_chain :simplified_type, :uuid
end
end
module PostgreSQLColumn
extend ActiveSupport::Concern
included do
def type_cast_with_uuid(value)
return UUIDTools::UUID.serialize(value) if type == :uuid
type_cast_without_uuid(value)
end
alias_method_chain :type_cast, :uuid if ActiveRecord::VERSION::MAJOR >= 4
def simplified_type_with_pguuid(field_type)
return :uuid if field_type == 'uuid'
simplified_type_without_pguuid(field_type)
end
alias_method_chain :simplified_type, :pguuid
end
end
module Quoting
extend ActiveSupport::Concern
included do
def quote_with_visiting(value, column = nil)
value = UUIDTools::UUID.serialize(value) if column && column.type == :uuid
quote_without_visiting(value, column)
end
def type_cast_with_visiting(value, column = nil)
value = UUIDTools::UUID.serialize(value) if column && column.type == :uuid
type_cast_without_visiting(value, column)
end
def native_database_types_with_uuid
@native_database_types ||= native_database_types_without_uuid.merge(uuid: { name: 'binary', limit: 16 })
end
alias_method_chain :quote, :visiting
alias_method_chain :type_cast, :visiting
alias_method_chain :native_database_types, :uuid
end
end
module PostgreSQLQuoting
extend ActiveSupport::Concern
included do
def quote_with_visiting(value, column = nil)
value = UUIDTools::UUID.serialize(value) if column && column.type == :uuid
value = value.to_s if value.is_a? UUIDTools::UUID
quote_without_visiting(value, column)
end
def type_cast_with_visiting(value, column = nil)
value = UUIDTools::UUID.serialize(value) if column && column.type == :uuid
value = value.to_s if value.is_a? UUIDTools::UUID
type_cast_without_visiting(value, column)
end
def native_database_types_with_pguuid
@native_database_types ||= native_database_types_without_pguuid.merge(uuid: { name: 'uuid' })
end
alias_method_chain :quote, :visiting
alias_method_chain :type_cast, :visiting
alias_method_chain :native_database_types, :pguuid
end
end
def self.apply!
ActiveRecord::ConnectionAdapters::Table.send :include, Migrations if defined? ActiveRecord::ConnectionAdapters::Table
ActiveRecord::ConnectionAdapters::TableDefinition.send :include, Migrations if defined? ActiveRecord::ConnectionAdapters::TableDefinition
ActiveRecord::ConnectionAdapters::Column.send :include, Column
ActiveRecord::ConnectionAdapters::PostgreSQLColumn.send :include, PostgreSQLColumn if defined? ActiveRecord::ConnectionAdapters::PostgreSQLColumn
ActiveRecord::ConnectionAdapters::Mysql2Adapter.send :include, Quoting if defined? ActiveRecord::ConnectionAdapters::Mysql2Adapter
ActiveRecord::ConnectionAdapters::SQLite3Adapter.send :include, Quoting if defined? ActiveRecord::ConnectionAdapters::SQLite3Adapter
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send :include, PostgreSQLQuoting if defined? ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
end
end
end
| 36.814516 | 154 | 0.691347 |
e9575b67b726aa26bce7aa0cfdfc5a069dee263b | 2,610 | module Pod
class ConfigureTVOS
attr_reader :configurator
def self.perform(options)
new(options).perform
end
def initialize(options)
@configurator = options.fetch(:configurator)
end
def perform
keep_demo = configurator.ask_with_answers("Would you like to include a demo application with your library", ["Yes", "No"]).to_sym
framework = configurator.ask_with_answers("Which testing frameworks will you use", ["Specta", "Kiwi", "None"]).to_sym
case framework
when :specta
configurator.add_pod_to_podfile "Specta"
configurator.add_pod_to_podfile "Expecta"
configurator.add_line_to_pch "@import Specta;"
configurator.add_line_to_pch "@import Expecta;"
configurator.set_test_framework("specta", "m", "tvos")
when :kiwi
configurator.add_pod_to_podfile "Kiwi"
configurator.add_line_to_pch "@import Kiwi;"
configurator.set_test_framework("kiwi", "m", "tvos")
when :none
configurator.set_test_framework("xctest", "m", "tvos")
end
snapshots = configurator.ask_with_answers("Would you like to do view based testing", ["Yes", "No"]).to_sym
case snapshots
when :yes
configurator.add_pod_to_podfile "FBSnapshotTestCase"
configurator.add_line_to_pch "@import FBSnapshotTestCase;"
if keep_demo == :no
puts " Putting demo application back in, you cannot do view tests without a host application."
keep_demo = :yes
end
if framework == :specta
configurator.add_pod_to_podfile "Expecta+Snapshots"
configurator.add_line_to_pch "@import Expecta_Snapshots;"
end
end
prefix = nil
loop do
prefix = configurator.ask("What is your class prefix").upcase
if prefix.include?(' ')
puts 'Your class prefix cannot contain spaces.'.red
else
break
end
end
Pod::ProjectManipulator.new({
:configurator => @configurator,
:xcodeproj_path => "templates/tvos/Example/PROJECT.xcodeproj",
:platform => :tvos,
:remove_demo_project => (keep_demo == :no),
:prefix => prefix
}).run
# There has to be a single file in the Classes dir
# or a framework won't be created, which is now default
`touch Pod/Classes/ReplaceMe.m`
`mv ./templates/tvos/* ./`
# remove podspec for osx
`rm ./NAME-osx.podspec`
`mv ./NAME-tvos.podspec ./NAME.podspec`
end
end
end
| 29.659091 | 135 | 0.627203 |
01001c4da270d8557dabc40c7d942873625ef596 | 1,942 | require_relative '../core/service'
require_relative '../console/colour'
require_relative '../console'
class ConsoleHostService < Service
provided_features :console_host
def initialize(io_in, io_out, io_err)
super
@io_in = io_in
@io_out = io_out
@io_err = io_err
end
def in
@io_in
end
def out
@io_out
end
def err
@io_err
end
end
class ConsoleService < SimpleService
required_features :framework, :console_host
optional_features :config
provided_features :console
def start
sleep 0.1 # <- wtf hack to allow asynchronous calls, Celluloid srsly?
@running = true
@console_host.out.puts 'Console service started'
if [email protected]? and @config[:mode] == "dumb"
@console = DumbConsole.new
else
@console = Console.new
end
@console.interpreter.register_helper :framework, @framework
end
def prompt
"> "
end
def show_prompt
@console_host.out.print @console.prompt
end
def welcome
@console_host.out.puts "#{'Toolbox'.blue} #{'RSGi'.red} 4.0"
end
def running?
@running
end
def read_input
# @console_host.in.gets
@console.read_input
end
def process_input(raw_input)
@console.process_input raw_input
end
def register_mode(mode)
@console.interpreter.register_mode mode, :local
end
def unregister_mode(mode)
@console.interpreter.unregister_mode mode
end
def register_command(mode_id, command)
mode = @console.interpreter.modes.mode(mode_id)
binding.pry
end
def unregister_command(mode_id, command_id)
# TODO this operation is currently unsupported
end
def register_helper(helper_id, helper)
@console.interpreter.register_helper helper_id, helper
end
end
| 20.229167 | 77 | 0.632853 |
e2d8850fc39ec58c803223a066915cbd6d916ba7 | 320 | module Types
class FollowingType < Types::BaseObject
field :id, ID, null: false
field :follower_id, Integer, null: true
field :followed_id, Integer, null: true
field :created_at, GraphQL::Types::ISO8601DateTime, null: false
field :updated_at, GraphQL::Types::ISO8601DateTime, null: false
end
end
| 32 | 67 | 0.725 |
01d1bb506fa52d6ec8846d152b8fbead76b617e7 | 1,076 |
class Game
class << self
def dfs24(item, index)
$r << item
$book[index] = true
if $r.size == 7
rc = $r.join('')
rs = eval rc rescue 0 # 使用ruby eval 进行执行
if rs == 24
puts rc+"=24"
end
end
$a.each_with_index do |ai, ix| # 循环 item的下一个结点元素,理论上是$a数组中除了自己的其他任意元素
if $book[ix] != true # 排除已经取出过的元素
$mc.each do |mi|
$r << mi # 取一个运算符加入到数组
dfs24(ai, ix)
$r.pop # 出一个数字
$r.pop # 出数字前面的运算符合
$book[ix] = false # 回退到上一个结点了,设置book对应索引值为false
end
end
end
end
def count24
$a = [1,0,0,23]
$mc = ['+', '-', '*', '/']
$a.each_with_index do |item, index|
$r = []
$book = [false, false, false, false]
dfs24(item, index)
end
end
end
end
Game.count24
# 想必大家都玩过一个游戏,叫做“24点”:给出4个整数,要求用加减乘除4个运算使其运算结果变成24
# 例如给出4个数:1、2、3、4。我可以用以下运算得到结果24:
# 1*2*3*4 = 24;2*3*4/1 = 24
# 上面的算法是类似全排列,会取到实际上是重复的算式,因为上面是按照图的数据结构做的,
# 如果按照二叉树的数据结构做,应该就能避免重复性质的算式 | 19.563636 | 76 | 0.511152 |
d5e50ceb1541993039e9339633fa7efd9d1755a3 | 1,668 | class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[5.1]
def change
create_table(:users, id: :uuid) do |t|
## Required
t.string :provider, :null => false, :default => "email"
t.string :uid, :null => false, :default => ""
## Database authenticatable
t.string :encrypted_password, :null => false, :default => ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
t.boolean :allow_password_change, :default => false
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0, :null => false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
## User Info
t.string :username
t.string :email
## Tokens
t.json :tokens
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, [:uid, :provider], unique: true
add_index :users, :reset_password_token, unique: true
add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
| 30.888889 | 110 | 0.63729 |
bf8361dfb35fd888acb74ef106084dfc259cb662 | 588 | module Talkable
module API
class Origin < Base
AFFILIATE_MEMBER = "AffiliateMember".freeze
PURCHASE = "Purchase".freeze
EVENT = "Event".freeze
DEFAULT_TRAFFIC_SOURCE = 'talkable-gem'
class << self
def create(origin_type, params)
post '/origins', {
type: origin_type,
data: default_data.merge(params),
}
end
protected
def default_data
{
traffic_source: DEFAULT_TRAFFIC_SOURCE,
}
end
end
end
end
end
| 20.275862 | 51 | 0.530612 |
33d11c2621c600ac54a5bec13fd85ce7bd357af4 | 425 | module MusicStory::Model
class Batch < ThinModels::Struct
attribute :path
attribute :state
DATE_PATTERN = /([0-9]{4})\-([0-9]{2})\-([0-9]{2})/
def date
m = DATE_PATTERN.match(File.basename(path))
m && Date.new(m[1].to_i, m[2].to_i, m[3].to_i)
end
def to_s
"#<Batch path=#{path}>"
end
def ==(rhs)
rhs && rhs.is_a?(Batch) && rhs.path == self.path
end
end
end
| 19.318182 | 55 | 0.548235 |
4ad03d19f7d0c635b01f5da4d9c9a67c8eb9b9cf | 798 | require File.expand_path("../../../kernel_v2/config/ssh", __FILE__)
module VagrantPlugins
module CommunicatorWinSSH
class Config < VagrantPlugins::Kernel_V2::SSHConfig
def finalize!
@shell = "cmd" if @shell == UNSET_VALUE
@sudo_command = "%c" if @sudo_command == UNSET_VALUE
if @export_command_template == UNSET_VALUE
if @shell == "cmd"
@export_command_template = 'set %ENV_KEY%="%ENV_VALUE%"'
else
@export_command_template = '$env:%ENV_KEY%="%ENV_VALUE%"'
end
end
super
end
def to_s
"WINSSH"
end
# Remove configuration options from regular SSH that are
# not used within this communicator
undef :forward_x11
undef :pty
end
end
end
| 25.741935 | 69 | 0.605263 |
f7e138e327d7a543b852478e66ca7d3b08473e0d | 1,099 | # frozen_string_literal: true
require "rails_helper"
require File.expand_path("../../support/shared_contexts/work_forms_context", __dir__)
RSpec.describe Hyrax::DenverBookChapterForm do
include_context "work forms context" do
describe "#required_fields" do
subject { form.required_fields }
it { is_expected.to eq %i[title creator resource_type book_title rights_statement] }
end
describe "#terms" do
subject(:terms) { form.terms }
it "sets the terms" do
expected_terms = %i[title alt_title resource_type creator institution abstract keyword
subject_text org_unit date_published book_title alt_book_title edition
pagination alternate_identifier library_of_congress_classification
related_identifier isbn publisher place_of_publication license
rights_holder rights_statement contributor editor medium language
time refereed add_info]
is_expected.to include(*expected_terms)
end
end
end
end
| 37.896552 | 98 | 0.682439 |
01fb5794929b149e017709bb3f341b098a5dcc97 | 2,901 | # Copyright (c) 2018 Public Library of Science
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
module TahiPusher
class ChannelResourceNotFound < StandardError; end
class ChannelName
CHANNEL_SEPARATOR = "-".freeze
MODEL_SEPARATOR = "@".freeze
PRESENCE = "presence".freeze
PRIVATE = "private".freeze
PUBLIC = "public".freeze
SYSTEM = "system".freeze
ADMIN = "admin".freeze
# <#Paper:1234 @id=4> --> "private-paper@4"
def self.build(target:, access:)
raise ChannelResourceNotFound.new("Channel target cannot be nil") if target.nil?
prefix = access unless access == PUBLIC
suffix = if target.is_a?(ActiveRecord::Base)
[target.class.name.underscore, target.id].join(MODEL_SEPARATOR)
else
target
end
[prefix, suffix].compact.join(CHANNEL_SEPARATOR)
end
# "private-paper@4" --> <#TahiPusher::ChannelName @prefix="private" @suffix="paper@4">
def self.parse(channel_name)
new(channel_name)
end
attr_reader :name, :prefix, :suffix
def initialize(name)
@name = name
@prefix, _, @suffix = name.rpartition(CHANNEL_SEPARATOR)
end
def access
prefix.presence || PUBLIC
end
def target
model, _, id = suffix.partition(MODEL_SEPARATOR)
if active_record_backed?
model.classify.constantize.find(id)
else
model
end
rescue ActiveRecord::RecordNotFound
raise ChannelResourceNotFound
end
# "private-paper@4" --> true, "system" --> false
def active_record_backed?
model, _ = suffix.partition(MODEL_SEPARATOR)
return false if model == SYSTEM
model.classify.constantize.new.is_a?(ActiveRecord::Base)
rescue NameError
false # model could not be constantized
end
end
end
| 34.535714 | 90 | 0.683557 |
3902e2c936252461c9c61064b779870c88e4ca76 | 317 | class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :title
t.text :description
t.decimal :price
t.decimal :size
t.boolean :is_spicy
t.boolean :is_veg
t.boolean :is_best_offer
t.string :path_to_image
t.timestamps
end
end
end
| 17.611111 | 46 | 0.681388 |
f86f848c27f8b4224d0466fa9f8e9a94cdc54a8d | 6,449 | =begin
#Xero Payroll AU
#This is the Xero Payroll API for orgs in Australia region.
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.3.1
=end
require 'time'
require 'date'
module XeroRuby::PayrollAu
require 'bigdecimal'
class Employees
attr_accessor :employees
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'employees' => :'Employees'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'employees' => :'Array<Employee>'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `XeroRuby::PayrollAu::Employees` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `XeroRuby::PayrollAu::Employees`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'employees')
if (value = attributes[:'employees']).is_a?(Array)
self.employees = value
end
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
employees == o.employees
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[employees].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(parse_date(value))
when :Date
Date.parse(parse_date(value))
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BigDecimal
BigDecimal(value.to_s)
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
XeroRuby::PayrollAu.const_get(type).build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash(downcase: true)
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
key = downcase ? attr : param
hash[key] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
def parse_date(datestring)
if datestring.include?('Date')
seconds_since_epoch = datestring.scan(/[0-9]+/)[0].to_i / 1000.0
Time.at(seconds_since_epoch).utc.strftime('%Y-%m-%dT%H:%M:%S%z').to_s
else # handle date 'types' for small subset of payroll API's
Time.parse(datestring).strftime('%Y-%m-%dT%H:%M:%S').to_s
end
end
end
end
| 30.135514 | 208 | 0.623508 |
0138235d91a9f7e0825438d9c729484a03200042 | 1,435 | require 'rails_helper'
RSpec.describe YarnProductPolicy do
subject { described_class }
permissions :update? do
let(:record) { build :yarn_product, created_by: 47, created_at: try(:created_at) || Time.current }
context 'when user is a maintainer' do
let(:user) { build :user, :maintainer }
it { is_expected.to permit user, record }
end
context 'when user is not a maintainer' do
let(:user) { build :user, id: 47 }
context 'when user created the record' do
context 'when record is less than eight days old' do
let(:created_at) { Time.current - 1.day }
it { is_expected.to permit user, record }
end
context 'when record is more than eight days old' do
let(:created_at) { Time.current - 9.days }
it { is_expected.to_not permit user, record }
end
end
context 'when user did not create the record' do
let(:user) { build :user, id: 23 }
it { is_expected.to_not permit user, record }
end
end
end
permissions :edit_referral_links? do
let(:record) { build :yarn_product }
context 'when user is a maintainer' do
let(:user) { build :user, :maintainer }
it { is_expected.to permit user, record }
end
context 'when user is not a maintainer' do
let(:user) { build :user }
it { is_expected.to_not permit user, record }
end
end
end
| 25.625 | 102 | 0.625087 |
e2147f81db13e50a9605e69cef5a19aafa9a8573 | 7,223 | # frozen_string_literal: true
require "spec_helper"
require "shared_contexts"
require "dependabot/dependency"
require "dependabot/dependency_file"
require "dependabot/bundler/update_checker/force_updater"
RSpec.describe Dependabot::Bundler::UpdateChecker::ForceUpdater do
include_context "stub rubygems compact index"
let(:updater) do
described_class.new(
dependency: dependency,
dependency_files: dependency_files,
target_version: target_version,
requirements_update_strategy: update_strategy,
credentials: [{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}]
)
end
let(:dependency_files) { [gemfile, lockfile] }
let(:dependency) do
Dependabot::Dependency.new(
name: dependency_name,
version: current_version,
requirements: requirements,
package_manager: "bundler"
)
end
let(:dependency_name) { "rspec-mocks" }
let(:current_version) { "3.5.0" }
let(:target_version) { "3.6.0" }
let(:update_strategy) { :bump_versions }
let(:requirements) do
[{
file: "Gemfile",
requirement: "~> 3.5.0",
groups: [:default],
source: nil
}]
end
let(:expected_requirements) do
[{
file: "Gemfile",
requirement: "~> 3.6.0",
groups: [:default],
source: nil
}]
end
let(:gemfile) do
Dependabot::DependencyFile.new(content: gemfile_body, name: "Gemfile")
end
let(:lockfile) do
Dependabot::DependencyFile.new(content: lockfile_body, name: "Gemfile.lock")
end
describe "#updated_dependencies" do
subject(:updated_dependencies) { updater.updated_dependencies }
context "when updating the dependency that requires the other" do
let(:gemfile_body) { fixture("ruby", "gemfiles", "version_conflict") }
let(:lockfile_body) do
fixture("ruby", "lockfiles", "version_conflict.lock")
end
let(:target_version) { "3.6.0" }
let(:dependency_name) { "rspec-mocks" }
let(:requirements) do
[{
file: "Gemfile",
requirement: "3.5.0",
groups: [:default],
source: nil
}]
end
let(:expected_requirements) do
[{
file: "Gemfile",
requirement: "3.6.0",
groups: [:default],
source: nil
}]
end
it "returns the right array of updated dependencies" do
expect(updated_dependencies).to eq(
[
Dependabot::Dependency.new(
name: "rspec-mocks",
version: "3.6.0",
previous_version: "3.5.0",
requirements: expected_requirements,
previous_requirements: requirements,
package_manager: "bundler"
),
Dependabot::Dependency.new(
name: "rspec-support",
version: "3.6.0",
previous_version: "3.5.0",
requirements: expected_requirements,
previous_requirements: requirements,
package_manager: "bundler"
)
]
)
end
end
context "when updating the dependency that is required by the other" do
let(:gemfile_body) { fixture("ruby", "gemfiles", "version_conflict") }
let(:lockfile_body) do
fixture("ruby", "lockfiles", "version_conflict.lock")
end
let(:target_version) { "3.6.0" }
let(:dependency_name) { "rspec-support" }
let(:requirements) do
[{
file: "Gemfile",
requirement: "3.5.0",
groups: [:default],
source: nil
}]
end
let(:expected_requirements) do
[{
file: "Gemfile",
requirement: "3.6.0",
groups: [:default],
source: nil
}]
end
it "returns the right array of updated dependencies" do
expect(updated_dependencies).to eq(
[
Dependabot::Dependency.new(
name: "rspec-support",
version: "3.6.0",
previous_version: "3.5.0",
requirements: expected_requirements,
previous_requirements: requirements,
package_manager: "bundler"
),
Dependabot::Dependency.new(
name: "rspec-mocks",
version: "3.6.0",
previous_version: "3.5.0",
requirements: expected_requirements,
previous_requirements: requirements,
package_manager: "bundler"
)
]
)
end
end
context "when two dependencies require the same subdependency" do
let(:gemfile_body) do
fixture("ruby", "gemfiles", "version_conflict_mutual_sub")
end
let(:lockfile_body) do
fixture("ruby", "lockfiles", "version_conflict_mutual_sub.lock")
end
let(:dependency_name) { "rspec-mocks" }
let(:target_version) { "3.6.0" }
let(:requirements) do
[{
file: "Gemfile",
requirement: "~> 3.5.0",
groups: [:default],
source: nil
}]
end
let(:expected_requirements) do
[{
file: "Gemfile",
requirement: "~> 3.6.0",
groups: [:default],
source: nil
}]
end
it "returns the right array of updated dependencies" do
expect(updated_dependencies).to eq(
[
Dependabot::Dependency.new(
name: "rspec-mocks",
version: "3.6.0",
previous_version: "3.5.0",
requirements: expected_requirements,
previous_requirements: requirements,
package_manager: "bundler"
),
Dependabot::Dependency.new(
name: "rspec-expectations",
version: "3.6.0",
previous_version: "3.5.0",
requirements: expected_requirements,
previous_requirements: requirements,
package_manager: "bundler"
)
]
)
end
end
context "when another dependency would need to be downgraded" do
let(:gemfile_body) do
fixture("ruby", "gemfiles", "version_conflict_requires_downgrade")
end
let(:lockfile_body) do
fixture("ruby", "lockfiles", "version_conflict_requires_downgrade.lock")
end
let(:target_version) { "0.8.6" }
let(:dependency_name) { "i18n" }
it "raises a resolvability error" do
expect { updater.updated_dependencies }.
to raise_error(Dependabot::DependencyFileNotResolvable)
end
end
context "when the ruby version would need to change" do
let(:gemfile_body) do
fixture("ruby", "gemfiles", "legacy_ruby")
end
let(:lockfile_body) do
fixture("ruby", "lockfiles", "legacy_ruby.lock")
end
let(:target_version) { "2.0.5" }
let(:dependency_name) { "public_suffix" }
it "raises a resolvability error" do
expect { updater.updated_dependencies }.
to raise_error(Dependabot::DependencyFileNotResolvable)
end
end
end
end
| 29.242915 | 80 | 0.568877 |
039f4d05334489e063de4678befbcb0be1bab502 | 961 | require_relative '../../wrappers/Ruby/aergo.rb'
aergo = Aergo.new("testnet-api.aergo.io", 7845)
account = AergoAPI::Account.new
# set the private key
account[:privkey] = "\xDB\x85\xDD\x0C\xBA\x47\x32\xA1\x1A\xEB\x3C\x7C\x48\x91\xFB\xD2\xFE\xC4\x5F\xC7\x2D\xB3\x3F\xB6\x1F\x31\xEB\x57\xE7\x24\x61\x76"
# or use an account on Ledger Nano S
#account[:use_ledger] = true
#account[:index] = 0
ContractCallback = Proc.new do |context, receipt|
puts "status : " + receipt[:status]
puts "return : " + receipt[:ret]
puts "BlockNo: " + receipt[:blockNo].to_s
puts "TxIndex: " + receipt[:txIndex].to_s
puts "GasUsed: " + receipt[:gasUsed].to_s
puts "feeUsed: " + receipt[:feeUsed].to_s
end
ret = aergo.call_smart_contract_async(
ContractCallback,
nil,
account,
"AmgLnRaGFLyvCPCEMHYJHooufT1c1pENTRGeV78WNPTxwQ2RYUW7",
"set_name",
"Ruby")
while aergo.process_requests(5000) > 0
# loop
end
| 30.03125 | 150 | 0.669095 |
910e8fe399de0271269f0b9d0dedc39d0100a4f3 | 773 | Pod::Spec.new do |s|
s.name = 'VENTouchLock'
s.version = '1.0.6'
s.summary = 'A passcode framework that features Touch ID'
s.description = <<-DESC
An easy to use passcode framework used in the Venmo app.
DESC
s.homepage = 'https://www.github.com/venmo/VENTouchLock'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Venmo' => '[email protected]'}
s.source = { :git => 'https://github.com/normKei/VENTouchLock.git', :tag => "v#{s.version}"}
s.source_files = 'VENTouchLock/**/*.{h,m}'
s.resources = ["VENTouchLock/**/*.{xib}"]
s.dependency 'SSKeychain', '~> 1.0'
s.frameworks = 'LocalAuthentication'
s.platform = :ios, '7.0'
s.requires_arc = true
end
| 40.684211 | 100 | 0.569211 |
1838246f80f55e7875b4199492f554774d8421af | 129 | class RemoveStageFromStartups < ActiveRecord::Migration[4.2]
def change
remove_column :startups, :stage, :string
end
end
| 21.5 | 60 | 0.75969 |
7a8c696b077952ac62e99176e41d08dadc008e66 | 294 | class CreatePictureLists < ActiveRecord::Migration
def self.up
ActiveRecord::Base.transaction do
create_table :picture_lists do |t|
t.timestamps
end
end
end
def self.down
ActiveRecord::Base.transaction do
drop_table :picture_lists
end
end
end
| 18.375 | 50 | 0.687075 |
bbf08801a5c7c28f25f21a40fdb545a447153331 | 3,213 | require 'spec_helper'
require 'yaml'
require 'ruby-swagger/data/operation'
describe Swagger::Data::Operation do
let(:payload) do
{
'tags' => ['pet'],
'summary' => 'Updates a pet in the store with form data',
'description' => 'Zippo',
'operationId' => 'updatePetWithForm',
'consumes' => ['application/x-www-form-urlencoded'],
'produces' => ['application/json', 'application/xml'],
'parameters' => [
{
'name' => 'petId',
'in' => 'path',
'description' => 'ID of pet that needs to be updated',
'required' => true,
'type' => 'string'
},
{
'name' => 'name',
'in' => 'formData',
'description' => 'Updated name of the pet',
'required' => false,
'type' => 'string'
},
{
'name' => 'status',
'in' => 'formData',
'description' => 'Updated status of the pet',
'required' => false,
'type' => 'string'
}
],
'responses' => {
'200' => {
'description' => 'Pet updated.'
},
'405' => {
'description' => 'Invalid input'
}
},
'security' => [
{
'petstore_auth' => [
'write:pets',
'read:pets'
]
}
]
}
end
context 'when parsing' do
it 'should create a valid Swagger::Data::Operation' do
parsed = Swagger::Data::Operation.parse(payload)
expect(parsed.tags).to eq ['pet']
expect(parsed.summary).to eq 'Updates a pet in the store with form data'
expect(parsed.description).to eq 'Zippo'
expect(parsed.operationId).to eq 'updatePetWithForm'
expect(parsed.consumes).to eq ['application/x-www-form-urlencoded']
expect(parsed.produces).to eq ['application/json', 'application/xml']
expect(parsed.parameters.count).to eq 3
expect(parsed.responses['200'].description).to eq 'Pet updated.'
expect(parsed.responses['405'].description).to eq 'Invalid input'
expect(parsed.security.first['petstore_auth']).to eq ['write:pets', 'read:pets']
end
end
context 'when creating the object' do
let(:object) do
Swagger::Data::Operation.parse(payload)
end
it 'should convert it to a valid JSON' do
parsed = OpenStruct.new JSON.parse(object.to_json)
expect(parsed.tags).to eq ['pet']
expect(parsed.summary).to eq 'Updates a pet in the store with form data'
expect(parsed.description).to eq 'Zippo'
expect(parsed.operationId).to eq 'updatePetWithForm'
expect(parsed.consumes).to eq ['application/x-www-form-urlencoded']
expect(parsed.produces).to eq ['application/json', 'application/xml']
expect(parsed.parameters.count).to eq 3
expect(parsed.responses['200']['description']).to eq 'Pet updated.'
expect(parsed.responses['405']['description']).to eq 'Invalid input'
expect(parsed.security.first['petstore_auth']).to eq ['write:pets', 'read:pets']
end
it 'should convert it to a valid YAML' do
expect { OpenStruct.new(YAML.load(object.to_yaml)) }.to_not raise_error
end
end
end
| 32.785714 | 86 | 0.577653 |
b957e24abe0ec76a21d32666e473c7f2d959cb19 | 4,067 | # frozen_string_literal: true
require "pathname"
require "rbconfig"
module Spec
module Path
def root
@root ||= Pathname.new(ruby_core? ? "../../../.." : "../../..").expand_path(__FILE__)
end
def gemspec
@gemspec ||= root.join(ruby_core? ? "lib/bundler/bundler.gemspec" : "bundler.gemspec")
end
def gemspec_dir
@gemspec_dir ||= gemspec.parent
end
def bindir
@bindir ||= root.join(ruby_core? ? "libexec" : "exe")
end
def gem_bin
@gem_bin ||= ruby_core? ? ENV["GEM_COMMAND"] : "#{Gem.ruby} --disable-gems -r#{spec_dir}/support/rubygems -S gem --backtrace"
end
def spec_dir
@spec_dir ||= root.join(ruby_core? ? "spec/bundler" : "spec")
end
def tracked_files
@tracked_files ||= ruby_core? ? `git ls-files -z -- lib/bundler lib/bundler.rb spec/bundler man/bundler*` : `git ls-files -z`
end
def shipped_files
@shipped_files ||= ruby_core? ? `git ls-files -z -- lib/bundler lib/bundler.rb man/bundler* libexec/bundle*` : `git ls-files -z -- lib man exe CHANGELOG.md LICENSE.md README.md bundler.gemspec`
end
def lib_tracked_files
@lib_tracked_files ||= ruby_core? ? `git ls-files -z -- lib/bundler lib/bundler.rb` : `git ls-files -z -- lib`
end
def tmp(*path)
root.join("tmp", scope, *path)
end
def scope
test_number = ENV["TEST_ENV_NUMBER"]
return "1" if test_number.nil?
test_number.empty? ? "1" : test_number
end
def home(*path)
tmp.join("home", *path)
end
def default_bundle_path(*path)
if Bundler::VERSION.split(".").first.to_i < 3
system_gem_path(*path)
else
bundled_app(*[".bundle", ENV.fetch("BUNDLER_SPEC_RUBY_ENGINE", Gem.ruby_engine), RbConfig::CONFIG["ruby_version"], *path].compact)
end
end
def bundled_app(*path)
root = tmp.join("bundled_app")
FileUtils.mkdir_p(root)
root.join(*path)
end
alias_method :bundled_app1, :bundled_app
def bundled_app2(*path)
root = tmp.join("bundled_app2")
FileUtils.mkdir_p(root)
root.join(*path)
end
def vendored_gems(path = nil)
bundled_app(*["vendor/bundle", Gem.ruby_engine, RbConfig::CONFIG["ruby_version"], path].compact)
end
def cached_gem(path)
bundled_app("vendor/cache/#{path}.gem")
end
def base_system_gems
tmp.join("gems/base")
end
def file_uri_for(path)
protocol = "file://"
root = Gem.win_platform? ? "/" : ""
return protocol + "localhost" + root + path.to_s if RUBY_VERSION < "2.5"
protocol + root + path.to_s
end
def gem_repo1(*args)
tmp("gems/remote1", *args)
end
def gem_repo_missing(*args)
tmp("gems/missing", *args)
end
def gem_repo2(*args)
tmp("gems/remote2", *args)
end
def gem_repo3(*args)
tmp("gems/remote3", *args)
end
def gem_repo4(*args)
tmp("gems/remote4", *args)
end
def security_repo(*args)
tmp("gems/security_repo", *args)
end
def system_gem_path(*path)
tmp("gems/system", *path)
end
def lib_path(*args)
tmp("libs", *args)
end
def lib_dir
root.join("lib")
end
def global_plugin_gem(*args)
home ".bundle", "plugin", "gems", *args
end
def local_plugin_gem(*args)
bundled_app ".bundle", "plugin", "gems", *args
end
def tmpdir(*args)
tmp "tmpdir", *args
end
def with_root_gemspec
if ruby_core?
root_gemspec = root.join("bundler.gemspec")
spec = Gem::Specification.load(gemspec.to_s)
spec.bindir = "libexec"
File.open(root_gemspec.to_s, "w") {|f| f.write spec.to_ruby }
yield(root_gemspec)
FileUtils.rm(root_gemspec)
else
yield(gemspec)
end
end
def ruby_core?
# avoid to warnings
@ruby_core ||= nil
if @ruby_core.nil?
@ruby_core = true & ENV["GEM_COMMAND"]
else
@ruby_core
end
end
extend self
end
end
| 22.977401 | 199 | 0.601426 |
bf05aeafed59cf64196753ad8663c6eb9b91cbd7 | 332 | require "i18n"
I18n.load_path << File.expand_path("../responsys/i18n/en.yml", __FILE__)
I18n.locale = :en
I18n.enforce_available_locales = false
require "responsys/exceptions/all"
require "responsys/helper"
require "responsys/configuration"
require "responsys/api/client"
require "responsys/member"
require "responsys/repository"
| 25.538462 | 72 | 0.795181 |
87d035f271c6dfdf8407fc27eb68bda66699ed66 | 6,010 | require 'fileutils'
require 'colored2'
module Pod
class TemplateConfigurator
attr_reader :pod_name, :pods_for_podfile, :prefixes, :test_example_file, :username, :email
def initialize(pod_name)
@pod_name = pod_name
@pods_for_podfile = []
@prefixes = []
@message_bank = MessageBank.new(self)
end
def ask(question)
answer = ""
loop do
puts "\n#{question}?"
@message_bank.show_prompt
answer = gets.chomp
break if answer.length > 0
print "\nResposta obrigatória!"
end
answer
end
def ask_with_answers(question, possible_answers)
print "\n#{question}? ["
print_info = Proc.new {
possible_answers_string = possible_answers.each_with_index do |answer, i|
_answer = (i == 0) ? answer.underlined : answer
print " " + _answer
print(" /") if i != possible_answers.length-1
end
print " ]\n"
}
print_info.call
answer = ""
loop do
@message_bank.show_prompt
answer = gets.downcase.chomp
answer = "sim" if answer == "s"
answer = "não" if answer == "n"
answer = "nao" if answer == "n"
# default to first answer
if answer == ""
answer = possible_answers[0].downcase
print answer.yellow
end
break if possible_answers.map { |a| a.downcase }.include? answer
print "\nPossíveis respostas ["
print_info.call
end
answer
end
def run
@message_bank.welcome_message
platform = self.ask_with_answers("Qual plataforma você prefere", ["iOS", "macOS"]).to_sym
case platform
when :macos
ConfigureMacOSSwift.perform(configurator: self)
when :ios
framework = self.ask_with_answers("Qual linguagem você vai utilizar", ["Swift", "ObjC"]).to_sym
case framework
when :swift
ConfigureSwift.perform(configurator: self)
when :objc
ConfigureIOS.perform(configurator: self)
end
end
replace_variables_in_files
clean_template_files
rename_template_files
add_pods_to_podfile
customise_prefix
rename_classes_folder
ensure_carthage_compatibility
reinitialize_git_repo
run_pod_install
@message_bank.farewell_message
end
#----------------------------------------#
def ensure_carthage_compatibility
FileUtils.ln_s('Example/Pods/Pods.xcodeproj', '_Pods.xcodeproj')
end
def run_pod_install
puts "\nRunning " + "pod install".magenta + " em sua biblioteca."
puts ""
Dir.chdir("Example") do
system "pod install"
end
`git add Example/#{pod_name}.xcodeproj/project.pbxproj`
`git commit -m "Initial commit"`
end
def clean_template_files
["./**/.gitkeep", "configure", "_CONFIGURE.rb", "README.md", "LICENSE", "templates", "setup", "CODE_OF_CONDUCT.md"].each do |asset|
`rm -rf #{asset}`
end
end
def replace_variables_in_files
file_names = ['POD_LICENSE', 'POD_README.md', 'NAME.podspec', '.travis.yml', podfile_path]
file_names.each do |file_name|
text = File.read(file_name)
text.gsub!("${POD_NAME}", @pod_name)
text.gsub!("${REPO_NAME}", @pod_name.gsub('+', '-'))
text.gsub!("${USER_NAME}", user_name)
text.gsub!("${USER_EMAIL}", user_email)
text.gsub!("${YEAR}", year)
text.gsub!("${DATE}", date)
File.open(file_name, "w") { |file| file.puts text }
end
end
def add_pod_to_podfile podname
@pods_for_podfile << podname
end
def add_pods_to_podfile
podfile = File.read podfile_path
podfile_content = @pods_for_podfile.map do |pod|
"pod '" + pod + "'"
end.join("\n ")
podfile.gsub!("${INCLUDED_PODS}", podfile_content)
File.open(podfile_path, "w") { |file| file.puts podfile }
end
def add_line_to_pch line
@prefixes << line
end
def customise_prefix
prefix_path = "Example/Tests/Tests-Prefix.pch"
return unless File.exists? prefix_path
pch = File.read prefix_path
pch.gsub!("${INCLUDED_PREFIXES}", @prefixes.join("\n ") )
File.open(prefix_path, "w") { |file| file.puts pch }
end
def set_test_framework(test_type, extension, folder)
content_path = "setup/test_examples/" + test_type + "." + extension
tests_path = "templates/" + folder + "/Example/Tests/Tests." + extension
tests = File.read tests_path
tests.gsub!("${TEST_EXAMPLE}", File.read(content_path) )
File.open(tests_path, "w") { |file| file.puts tests }
end
def rename_template_files
FileUtils.mv "POD_README.md", "README.md"
FileUtils.mv "POD_LICENSE", "LICENSE"
FileUtils.mv "NAME.podspec", "#{pod_name}.podspec"
end
def rename_classes_folder
FileUtils.mv "Pod", @pod_name
end
def reinitialize_git_repo
`rm -rf .git`
`git init`
`git add -A`
end
def validate_user_details
return (user_email.length > 0) && (user_name.length > 0)
end
#----------------------------------------#
def user_name
(ENV['GIT_COMMITTER_NAME'] || github_user_name || `git config user.name` || `<GITHUB_USERNAME>` ).strip
end
def github_user_name
github_user_name = `security find-internet-password -s github.com | grep acct | sed 's/"acct"<blob>="//g' | sed 's/"//g'`.strip
is_valid = github_user_name.empty? or github_user_name.include? '@'
return is_valid ? nil : github_user_name
end
def user_email
(ENV['GIT_COMMITTER_EMAIL'] || `git config user.email`).strip
end
def year
Time.now.year.to_s
end
def date
Time.now.strftime "%m/%d/%Y"
end
def podfile_path
'Example/Podfile'
end
#----------------------------------------#
end
end
| 26.59292 | 137 | 0.597171 |
91981b8231b9e34cd793b1e308b4b3b91b62601e | 691 | # -*- encoding : utf-8 -*-
module Satrap
class HttpClient
def self.call(uri, xml)
new(uri, xml).call
end
def call
http.post(uri.path, xml, headers)
end
private
attr_reader :uri, :xml
def initialize(uri, xml)
@uri = uri
@xml = xml
end
def headers
{
'Content-Type' => 'text/xml'
}
end
def http
http = Net::HTTP.new(uri.host, uri.port)
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.ca_file = ca_file
http.use_ssl = true
http.ssl_version = :TLSv1
http
end
def ca_file
File.dirname(__FILE__) + '/../../ssl-certs/ca_bundle.crt'
end
end
end
| 16.853659 | 63 | 0.557164 |
1ae2ef2a6853f57e3769df2341a62e49b67a323f | 79 | # frozen_string_literal: true
module FontAwesomeRails
VERSION = "0.1.0"
end
| 13.166667 | 29 | 0.759494 |
210e0f3af60b120ce27aa53782ba18bac08778c5 | 1,474 | require 'beaker-rspec'
require 'tmpdir'
require 'yaml'
require 'simp/beaker_helpers'
include Simp::BeakerHelpers
require 'beaker/puppet_install_helper'
unless ENV['BEAKER_provision'] == 'no'
hosts.each do |host|
# Install Puppet
if host.is_pe?
install_pe
else
install_puppet
end
include Simp::BeakerHelpers::Windows if is_windows?(host)
end
end
RSpec.configure do |c|
# ensure that environment OS is ready on each host
fix_errata_on(hosts)
# Readable test descriptions
c.formatter = :documentation
# Configure all nodes in nodeset
c.before :suite do
begin
# Install modules and dependencies from spec/fixtures/modules
copy_fixture_modules_to( hosts )
nonwin = hosts.dup
nonwin.delete_if {|h| h[:platform] =~ /windows/ }
unless nonwin.empty?
begin
server = only_host_with_role(nonwin, 'server')
rescue ArgumentError => e
server = hosts_with_role(nonwin, 'default').first
end
# Generate and install PKI certificates on each SUT
Dir.mktmpdir do |cert_dir|
run_fake_pki_ca_on(server, nonwin, cert_dir )
nonwin.each{ |sut| copy_pki_to( sut, cert_dir, '/etc/pki/simp-testing' )}
end
# add PKI keys
copy_keydist_to(server)
end
rescue StandardError, ScriptError => e
if ENV['PRY']
require 'pry'; binding.pry
else
raise e
end
end
end
end
| 23.774194 | 83 | 0.651289 |
33c8017e3ef655ef2e7781ff7e4c4613fa626986 | 1,372 | # frozen_string_literal: true
require 'spec_helper'
describe 'apache::mod::lookup_identity', type: :class do
it_behaves_like 'a mod class, without including apache'
context 'default configuration with parameters' do
context 'on a Debian OS' do
let :facts do
{
lsbdistcodename: 'jessie',
osfamily: 'Debian',
operatingsystemrelease: '8',
id: 'root',
kernel: 'Linux',
operatingsystem: 'Debian',
path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
is_pe: false,
}
end
it { is_expected.to contain_class('apache') }
it { is_expected.to contain_package('libapache2-mod-lookup-identity') }
it { is_expected.to contain_apache__mod('lookup_identity') }
end # Debian
context 'on a RedHat OS' do
let :facts do
{
osfamily: 'RedHat',
operatingsystemrelease: '6',
id: 'root',
kernel: 'Linux',
operatingsystem: 'RedHat',
path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
is_pe: false,
}
end
it { is_expected.to contain_class('apache') }
it { is_expected.to contain_package('mod_lookup_identity') }
it { is_expected.to contain_apache__mod('lookup_identity') }
end # Redhat
end
end
| 29.191489 | 79 | 0.599125 |
33794dafc6d41af4fa28ff1e393a65405c4bad89 | 33,635 | #!/usr/bin/env rspec
require 'spec_helper'
describe Puppet::Resource::Catalog, "when compiling" do
include PuppetSpec::Files
before do
@basepath = make_absolute("/somepath")
# stub this to not try to create state.yaml
Puppet::Util::Storage.stubs(:store)
end
# audit only resources are unmanaged
# as are resources without properties with should values
it "should write its managed resources' types, namevars" do
catalog = Puppet::Resource::Catalog.new("host")
resourcefile = tmpfile('resourcefile')
Puppet[:resourcefile] = resourcefile
res = Puppet::Type.type('file').new(:title => File.expand_path('/tmp/sam'), :ensure => 'present')
res.file = 'site.pp'
res.line = 21
res2 = Puppet::Type.type('exec').new(:title => 'bob', :command => "#{File.expand_path('/bin/rm')} -rf /")
res2.file = File.expand_path('/modules/bob/manifests/bob.pp')
res2.line = 42
res3 = Puppet::Type.type('file').new(:title => File.expand_path('/tmp/susan'), :audit => 'all')
res3.file = 'site.pp'
res3.line = 63
res4 = Puppet::Type.type('file').new(:title => File.expand_path('/tmp/lilly'))
res4.file = 'site.pp'
res4.line = 84
comp_res = Puppet::Type.type('component').new(:title => 'Class[Main]')
catalog.add_resource(res, res2, res3, res4, comp_res)
catalog.write_resource_file
File.readlines(resourcefile).map(&:chomp).should =~ [
"file[#{File.expand_path('/tmp/sam')}]",
"exec[#{File.expand_path('/bin/rm')} -rf /]"
]
end
it "should log an error if unable to write to the resource file" do
catalog = Puppet::Resource::Catalog.new("host")
Puppet[:resourcefile] = File.expand_path('/not/writable/file')
catalog.add_resource(Puppet::Type.type('file').new(:title => File.expand_path('/tmp/foo')))
catalog.write_resource_file
@logs.size.should == 1
@logs.first.message.should =~ /Could not create resource file/
@logs.first.level.should == :err
end
it "should be able to write its list of classes to the class file" do
@catalog = Puppet::Resource::Catalog.new("host")
@catalog.add_class "foo", "bar"
Puppet.settings.expects(:value).with(:classfile).returns "/class/file"
fh = mock 'filehandle'
File.expects(:open).with("/class/file", "w").yields fh
fh.expects(:puts).with "foo\nbar"
@catalog.write_class_file
end
it "should have a client_version attribute" do
@catalog = Puppet::Resource::Catalog.new("host")
@catalog.client_version = 5
@catalog.client_version.should == 5
end
it "should have a server_version attribute" do
@catalog = Puppet::Resource::Catalog.new("host")
@catalog.server_version = 5
@catalog.server_version.should == 5
end
describe "when compiling" do
it "should accept tags" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one")
config.tags.should == %w{one}
end
it "should accept multiple tags at once" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one", "two")
config.tags.should == %w{one two}
end
it "should convert all tags to strings" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one", :two)
config.tags.should == %w{one two}
end
it "should tag with both the qualified name and the split name" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one::two")
config.tags.include?("one").should be_true
config.tags.include?("one::two").should be_true
end
it "should accept classes" do
config = Puppet::Resource::Catalog.new("mynode")
config.add_class("one")
config.classes.should == %w{one}
config.add_class("two", "three")
config.classes.should == %w{one two three}
end
it "should tag itself with passed class names" do
config = Puppet::Resource::Catalog.new("mynode")
config.add_class("one")
config.tags.should == %w{one}
end
end
describe "when converting to a RAL catalog" do
before do
@original = Puppet::Resource::Catalog.new("mynode")
@original.tag(*%w{one two three})
@original.add_class *%w{four five six}
@top = Puppet::Resource.new :class, 'top'
@topobject = Puppet::Resource.new :file, @basepath+'/topobject'
@middle = Puppet::Resource.new :class, 'middle'
@middleobject = Puppet::Resource.new :file, @basepath+'/middleobject'
@bottom = Puppet::Resource.new :class, 'bottom'
@bottomobject = Puppet::Resource.new :file, @basepath+'/bottomobject'
@resources = [@top, @topobject, @middle, @middleobject, @bottom, @bottomobject]
@original.add_resource(*@resources)
@original.add_edge(@top, @topobject)
@original.add_edge(@top, @middle)
@original.add_edge(@middle, @middleobject)
@original.add_edge(@middle, @bottom)
@original.add_edge(@bottom, @bottomobject)
@catalog = @original.to_ral
end
it "should add all resources as RAL instances" do
@resources.each { |resource| @catalog.resource(resource.ref).should be_instance_of(Puppet::Type) }
end
it "should copy the tag list to the new catalog" do
@catalog.tags.sort.should == @original.tags.sort
end
it "should copy the class list to the new catalog" do
@catalog.classes.should == @original.classes
end
it "should duplicate the original edges" do
@original.edges.each do |edge|
@catalog.edge?(@catalog.resource(edge.source.ref), @catalog.resource(edge.target.ref)).should be_true
end
end
it "should set itself as the catalog for each converted resource" do
@catalog.vertices.each { |v| v.catalog.object_id.should equal(@catalog.object_id) }
end
# This tests #931.
it "should not lose track of resources whose names vary" do
changer = Puppet::Resource.new :file, @basepath+'/test/', :parameters => {:ensure => :directory}
config = Puppet::Resource::Catalog.new('test')
config.add_resource(changer)
config.add_resource(@top)
config.add_edge(@top, changer)
catalog = config.to_ral
catalog.resource("File[#{@basepath}/test/]").should equal(changer)
catalog.resource("File[#{@basepath}/test]").should equal(changer)
end
after do
# Remove all resource instances.
@catalog.clear(true)
end
end
describe "when filtering" do
before :each do
@original = Puppet::Resource::Catalog.new("mynode")
@original.tag(*%w{one two three})
@original.add_class *%w{four five six}
@r1 = stub_everything 'r1', :ref => "File[/a]"
@r1.stubs(:respond_to?).with(:ref).returns(true)
@r1.stubs(:dup).returns(@r1)
@r1.stubs(:is_a?).with(Puppet::Resource).returns(true)
@r2 = stub_everything 'r2', :ref => "File[/b]"
@r2.stubs(:respond_to?).with(:ref).returns(true)
@r2.stubs(:dup).returns(@r2)
@r2.stubs(:is_a?).with(Puppet::Resource).returns(true)
@resources = [@r1,@r2]
@original.add_resource(@r1,@r2)
end
it "should transform the catalog to a resource catalog" do
@original.expects(:to_catalog).with { |h,b| h == :to_resource }
@original.filter
end
it "should scan each catalog resource in turn and apply filtering block" do
@resources.each { |r| r.expects(:test?) }
@original.filter do |r|
r.test?
end
end
it "should filter out resources which produce true when the filter block is evaluated" do
@original.filter do |r|
r == @r1
end.resource("File[/a]").should be_nil
end
it "should not consider edges against resources that were filtered out" do
@original.add_edge(@r1,@r2)
@original.filter do |r|
r == @r1
end.edge?(@r1,@r2).should_not be
end
end
describe "when functioning as a resource container" do
before do
@catalog = Puppet::Resource::Catalog.new("host")
@one = Puppet::Type.type(:notify).new :name => "one"
@two = Puppet::Type.type(:notify).new :name => "two"
@dupe = Puppet::Type.type(:notify).new :name => "one"
end
it "should provide a method to add one or more resources" do
@catalog.add_resource @one, @two
@catalog.resource(@one.ref).should equal(@one)
@catalog.resource(@two.ref).should equal(@two)
end
it "should add resources to the relationship graph if it exists" do
relgraph = @catalog.relationship_graph
@catalog.add_resource @one
relgraph.should be_vertex(@one)
end
it "should set itself as the resource's catalog if it is not a relationship graph" do
@one.expects(:catalog=).with(@catalog)
@catalog.add_resource @one
end
it "should make all vertices available by resource reference" do
@catalog.add_resource(@one)
@catalog.resource(@one.ref).should equal(@one)
@catalog.vertices.find { |r| r.ref == @one.ref }.should equal(@one)
end
it "should canonize how resources are referred to during retrieval when both type and title are provided" do
@catalog.add_resource(@one)
@catalog.resource("notify", "one").should equal(@one)
end
it "should canonize how resources are referred to during retrieval when just the title is provided" do
@catalog.add_resource(@one)
@catalog.resource("notify[one]", nil).should equal(@one)
end
it "should not allow two resources with the same resource reference" do
@catalog.add_resource(@one)
proc { @catalog.add_resource(@dupe) }.should raise_error(Puppet::Resource::Catalog::DuplicateResourceError)
end
it "should not store objects that do not respond to :ref" do
proc { @catalog.add_resource("thing") }.should raise_error(ArgumentError)
end
it "should remove all resources when asked" do
@catalog.add_resource @one
@catalog.add_resource @two
@one.expects :remove
@two.expects :remove
@catalog.clear(true)
end
it "should support a mechanism for finishing resources" do
@one.expects :finish
@two.expects :finish
@catalog.add_resource @one
@catalog.add_resource @two
@catalog.finalize
end
it "should make default resources when finalizing" do
@catalog.expects(:make_default_resources)
@catalog.finalize
end
it "should add default resources to the catalog upon creation" do
@catalog.make_default_resources
@catalog.resource(:schedule, "daily").should_not be_nil
end
it "should optionally support an initialization block and should finalize after such blocks" do
@one.expects :finish
@two.expects :finish
config = Puppet::Resource::Catalog.new("host") do |conf|
conf.add_resource @one
conf.add_resource @two
end
end
it "should inform the resource that it is the resource's catalog" do
@one.expects(:catalog=).with(@catalog)
@catalog.add_resource @one
end
it "should be able to find resources by reference" do
@catalog.add_resource @one
@catalog.resource(@one.ref).should equal(@one)
end
it "should be able to find resources by reference or by type/title tuple" do
@catalog.add_resource @one
@catalog.resource("notify", "one").should equal(@one)
end
it "should have a mechanism for removing resources" do
@catalog.add_resource @one
@one.expects :remove
@catalog.remove_resource(@one)
@catalog.resource(@one.ref).should be_nil
@catalog.vertex?(@one).should be_false
end
it "should have a method for creating aliases for resources" do
@catalog.add_resource @one
@catalog.alias(@one, "other")
@catalog.resource("notify", "other").should equal(@one)
end
it "should ignore conflicting aliases that point to the aliased resource" do
@catalog.alias(@one, "other")
lambda { @catalog.alias(@one, "other") }.should_not raise_error
end
it "should create aliases for isomorphic resources whose names do not match their titles" do
resource = Puppet::Type::File.new(:title => "testing", :path => @basepath+"/something")
@catalog.add_resource(resource)
@catalog.resource(:file, @basepath+"/something").should equal(resource)
end
it "should not create aliases for non-isomorphic resources whose names do not match their titles" do
resource = Puppet::Type.type(:exec).new(:title => "testing", :command => "echo", :path => %w{/bin /usr/bin /usr/local/bin})
@catalog.add_resource(resource)
# Yay, I've already got a 'should' method
@catalog.resource(:exec, "echo").object_id.should == nil.object_id
end
# This test is the same as the previous, but the behaviour should be explicit.
it "should alias using the class name from the resource reference, not the resource class name" do
@catalog.add_resource @one
@catalog.alias(@one, "other")
@catalog.resource("notify", "other").should equal(@one)
end
it "should fail to add an alias if the aliased name already exists" do
@catalog.add_resource @one
proc { @catalog.alias @two, "one" }.should raise_error(ArgumentError)
end
it "should not fail when a resource has duplicate aliases created" do
@catalog.add_resource @one
proc { @catalog.alias @one, "one" }.should_not raise_error
end
it "should not create aliases that point back to the resource" do
@catalog.alias(@one, "one")
@catalog.resource(:notify, "one").should be_nil
end
it "should be able to look resources up by their aliases" do
@catalog.add_resource @one
@catalog.alias @one, "two"
@catalog.resource(:notify, "two").should equal(@one)
end
it "should remove resource aliases when the target resource is removed" do
@catalog.add_resource @one
@catalog.alias(@one, "other")
@one.expects :remove
@catalog.remove_resource(@one)
@catalog.resource("notify", "other").should be_nil
end
it "should add an alias for the namevar when the title and name differ on isomorphic resource types" do
resource = Puppet::Type.type(:file).new :path => @basepath+"/something", :title => "other", :content => "blah"
resource.expects(:isomorphic?).returns(true)
@catalog.add_resource(resource)
@catalog.resource(:file, "other").should equal(resource)
@catalog.resource(:file, @basepath+"/something").ref.should == resource.ref
end
it "should not add an alias for the namevar when the title and name differ on non-isomorphic resource types" do
resource = Puppet::Type.type(:file).new :path => @basepath+"/something", :title => "other", :content => "blah"
resource.expects(:isomorphic?).returns(false)
@catalog.add_resource(resource)
@catalog.resource(:file, resource.title).should equal(resource)
# We can't use .should here, because the resources respond to that method.
raise "Aliased non-isomorphic resource" if @catalog.resource(:file, resource.name)
end
it "should provide a method to create additional resources that also registers the resource" do
args = {:name => "/yay", :ensure => :file}
resource = stub 'file', :ref => "File[/yay]", :catalog= => @catalog, :title => "/yay", :[] => "/yay"
Puppet::Type.type(:file).expects(:new).with(args).returns(resource)
@catalog.create_resource :file, args
@catalog.resource("File[/yay]").should equal(resource)
end
describe "when adding resources with multiple namevars" do
before :each do
Puppet::Type.newtype(:multiple) do
newparam(:color, :namevar => true)
newparam(:designation, :namevar => true)
def self.title_patterns
[ [
/^(\w+) (\w+)$/,
[
[:color, lambda{|x| x}],
[:designation, lambda{|x| x}]
]
] ]
end
end
end
it "should add an alias using the uniqueness key" do
@resource = Puppet::Type.type(:multiple).new(:title => "some resource", :color => "red", :designation => "5")
@catalog.add_resource(@resource)
@catalog.resource(:multiple, "some resource").must == @resource
@catalog.resource("Multiple[some resource]").must == @resource
@catalog.resource("Multiple[red 5]").must == @resource
end
it "should conflict with a resource with the same uniqueness key" do
@resource = Puppet::Type.type(:multiple).new(:title => "some resource", :color => "red", :designation => "5")
@other = Puppet::Type.type(:multiple).new(:title => "another resource", :color => "red", :designation => "5")
@catalog.add_resource(@resource)
expect { @catalog.add_resource(@other) }.to raise_error(ArgumentError, /Cannot alias Multiple\[another resource\] to \["red", "5"\].*resource \["Multiple", "red", "5"\] already declared/)
end
it "should conflict when its uniqueness key matches another resource's title" do
path = make_absolute("/tmp/foo")
@resource = Puppet::Type.type(:file).new(:title => path)
@other = Puppet::Type.type(:file).new(:title => "another file", :path => path)
@catalog.add_resource(@resource)
expect { @catalog.add_resource(@other) }.to raise_error(ArgumentError, /Cannot alias File\[another file\] to \["#{Regexp.escape(path)}"\].*resource \["File", "#{Regexp.escape(path)}"\] already declared/)
end
it "should conflict when its uniqueness key matches the uniqueness key derived from another resource's title" do
@resource = Puppet::Type.type(:multiple).new(:title => "red leader")
@other = Puppet::Type.type(:multiple).new(:title => "another resource", :color => "red", :designation => "leader")
@catalog.add_resource(@resource)
expect { @catalog.add_resource(@other) }.to raise_error(ArgumentError, /Cannot alias Multiple\[another resource\] to \["red", "leader"\].*resource \["Multiple", "red", "leader"\] already declared/)
end
end
end
describe "when applying" do
before :each do
@catalog = Puppet::Resource::Catalog.new("host")
@transaction = Puppet::Transaction.new(@catalog)
Puppet::Transaction.stubs(:new).returns(@transaction)
@transaction.stubs(:evaluate)
@transaction.stubs(:add_times)
@transaction.stubs(:for_network_device=)
Puppet.settings.stubs(:use)
end
it "should create and evaluate a transaction" do
@transaction.expects(:evaluate)
@catalog.apply
end
it "should provide the catalog retrieval time to the transaction" do
@catalog.retrieval_duration = 5
@transaction.expects(:add_times).with(:config_retrieval => 5)
@catalog.apply
end
it "should use a retrieval time of 0 if none is set in the catalog" do
@catalog.retrieval_duration = nil
@transaction.expects(:add_times).with(:config_retrieval => 0)
@catalog.apply
end
it "should return the transaction" do
@catalog.apply.should equal(@transaction)
end
it "should yield the transaction if a block is provided" do
@catalog.apply do |trans|
trans.should equal(@transaction)
end
end
it "should default to being a host catalog" do
@catalog.host_config.should be_true
end
it "should be able to be set to a non-host_config" do
@catalog.host_config = false
@catalog.host_config.should be_false
end
it "should pass supplied tags on to the transaction" do
@transaction.expects(:tags=).with(%w{one two})
@catalog.apply(:tags => %w{one two})
end
it "should set ignoreschedules on the transaction if specified in apply()" do
@transaction.expects(:ignoreschedules=).with(true)
@catalog.apply(:ignoreschedules => true)
end
describe "host catalogs" do
# super() doesn't work in the setup method for some reason
before do
@catalog.host_config = true
Puppet::Util::Storage.stubs(:store)
end
it "should initialize the state database before applying a catalog" do
Puppet::Util::Storage.expects(:load)
# Short-circuit the apply, so we know we're loading before the transaction
Puppet::Transaction.expects(:new).raises ArgumentError
proc { @catalog.apply }.should raise_error(ArgumentError)
end
it "should sync the state database after applying" do
Puppet::Util::Storage.expects(:store)
@transaction.stubs :any_failed? => false
@catalog.apply
end
after { Puppet.settings.clear }
end
describe "non-host catalogs" do
before do
@catalog.host_config = false
end
it "should never send reports" do
Puppet[:report] = true
Puppet[:summarize] = true
@catalog.apply
end
it "should never modify the state database" do
Puppet::Util::Storage.expects(:load).never
Puppet::Util::Storage.expects(:store).never
@catalog.apply
end
after { Puppet.settings.clear }
end
end
describe "when creating a relationship graph" do
before do
Puppet::Type.type(:component)
@catalog = Puppet::Resource::Catalog.new("host")
@compone = Puppet::Type::Component.new :name => "one"
@comptwo = Puppet::Type::Component.new :name => "two", :require => "Class[one]"
@file = Puppet::Type.type(:file)
@one = @file.new :path => @basepath+"/one"
@two = @file.new :path => @basepath+"/two"
@sub = @file.new :path => @basepath+"/two/subdir"
@catalog.add_edge @compone, @one
@catalog.add_edge @comptwo, @two
@three = @file.new :path => @basepath+"/three"
@four = @file.new :path => @basepath+"/four", :require => "File[#{@basepath}/three]"
@five = @file.new :path => @basepath+"/five"
@catalog.add_resource @compone, @comptwo, @one, @two, @three, @four, @five, @sub
@relationships = @catalog.relationship_graph
end
it "should be able to create a relationship graph" do
@relationships.should be_instance_of(Puppet::SimpleGraph)
end
it "should not have any components" do
@relationships.vertices.find { |r| r.instance_of?(Puppet::Type::Component) }.should be_nil
end
it "should have all non-component resources from the catalog" do
# The failures print out too much info, so i just do a class comparison
@relationships.vertex?(@five).should be_true
end
it "should have all resource relationships set as edges" do
@relationships.edge?(@three, @four).should be_true
end
it "should copy component relationships to all contained resources" do
@relationships.path_between(@one, @two).should be
end
it "should add automatic relationships to the relationship graph" do
@relationships.edge?(@two, @sub).should be_true
end
it "should get removed when the catalog is cleaned up" do
@relationships.expects(:clear)
@catalog.clear
@catalog.instance_variable_get("@relationship_graph").should be_nil
end
it "should write :relationships and :expanded_relationships graph files if the catalog is a host catalog" do
@catalog.clear
graph = Puppet::SimpleGraph.new
Puppet::SimpleGraph.expects(:new).returns graph
graph.expects(:write_graph).with(:relationships)
graph.expects(:write_graph).with(:expanded_relationships)
@catalog.host_config = true
@catalog.relationship_graph
end
it "should not write graph files if the catalog is not a host catalog" do
@catalog.clear
graph = Puppet::SimpleGraph.new
Puppet::SimpleGraph.expects(:new).returns graph
graph.expects(:write_graph).never
@catalog.host_config = false
@catalog.relationship_graph
end
it "should create a new relationship graph after clearing the old one" do
@relationships.expects(:clear)
@catalog.clear
@catalog.relationship_graph.should be_instance_of(Puppet::SimpleGraph)
end
it "should remove removed resources from the relationship graph if it exists" do
@catalog.remove_resource(@one)
@catalog.relationship_graph.vertex?(@one).should be_false
end
end
describe "when writing dot files" do
before do
@catalog = Puppet::Resource::Catalog.new("host")
@name = :test
@file = File.join(Puppet[:graphdir], @name.to_s + ".dot")
end
it "should only write when it is a host catalog" do
File.expects(:open).with(@file).never
@catalog.host_config = false
Puppet[:graph] = true
@catalog.write_graph(@name)
end
after do
Puppet.settings.clear
end
end
describe "when indirecting" do
before do
@real_indirection = Puppet::Resource::Catalog.indirection
@indirection = stub 'indirection', :name => :catalog
end
it "should use the value of the 'catalog_terminus' setting to determine its terminus class" do
# Puppet only checks the terminus setting the first time you ask
# so this returns the object to the clean state
# at the expense of making this test less pure
Puppet::Resource::Catalog.indirection.reset_terminus_class
Puppet.settings[:catalog_terminus] = "rest"
Puppet::Resource::Catalog.indirection.terminus_class.should == :rest
end
it "should allow the terminus class to be set manually" do
Puppet::Resource::Catalog.indirection.terminus_class = :rest
Puppet::Resource::Catalog.indirection.terminus_class.should == :rest
end
after do
@real_indirection.reset_terminus_class
end
end
describe "when converting to yaml" do
before do
@catalog = Puppet::Resource::Catalog.new("me")
@catalog.add_edge("one", "two")
end
it "should be able to be dumped to yaml" do
YAML.dump(@catalog).should be_instance_of(String)
end
end
describe "when converting from yaml" do
before do
@catalog = Puppet::Resource::Catalog.new("me")
@catalog.add_edge("one", "two")
text = YAML.dump(@catalog)
@newcatalog = YAML.load(text)
end
it "should get converted back to a catalog" do
@newcatalog.should be_instance_of(Puppet::Resource::Catalog)
end
it "should have all vertices" do
@newcatalog.vertex?("one").should be_true
@newcatalog.vertex?("two").should be_true
end
it "should have all edges" do
@newcatalog.edge?("one", "two").should be_true
end
end
end
describe Puppet::Resource::Catalog, "when converting to pson", :if => Puppet.features.pson? do
before do
@catalog = Puppet::Resource::Catalog.new("myhost")
end
def pson_output_should
@catalog.class.expects(:pson_create).with { |hash| yield hash }.returns(:something)
end
# LAK:NOTE For all of these tests, we convert back to the resource so we can
# trap the actual data structure then.
it "should set its document_type to 'Catalog'" do
pson_output_should { |hash| hash['document_type'] == "Catalog" }
PSON.parse @catalog.to_pson
end
it "should set its data as a hash" do
pson_output_should { |hash| hash['data'].is_a?(Hash) }
PSON.parse @catalog.to_pson
end
[:name, :version, :tags, :classes].each do |param|
it "should set its #{param} to the #{param} of the resource" do
@catalog.send(param.to_s + "=", "testing") unless @catalog.send(param)
pson_output_should { |hash| hash['data'][param.to_s] == @catalog.send(param) }
PSON.parse @catalog.to_pson
end
end
it "should convert its resources to a PSON-encoded array and store it as the 'resources' data" do
one = stub 'one', :to_pson_data_hash => "one_resource", :ref => "Foo[one]"
two = stub 'two', :to_pson_data_hash => "two_resource", :ref => "Foo[two]"
@catalog.add_resource(one)
@catalog.add_resource(two)
# TODO this should really guarantee sort order
PSON.parse(@catalog.to_pson,:create_additions => false)['data']['resources'].sort.should == ["one_resource", "two_resource"].sort
end
it "should convert its edges to a PSON-encoded array and store it as the 'edges' data" do
one = stub 'one', :to_pson_data_hash => "one_resource", :ref => 'Foo[one]'
two = stub 'two', :to_pson_data_hash => "two_resource", :ref => 'Foo[two]'
three = stub 'three', :to_pson_data_hash => "three_resource", :ref => 'Foo[three]'
@catalog.add_edge(one, two)
@catalog.add_edge(two, three)
@catalog.edges_between(one, two )[0].expects(:to_pson_data_hash).returns "one_two_pson"
@catalog.edges_between(two, three)[0].expects(:to_pson_data_hash).returns "two_three_pson"
PSON.parse(@catalog.to_pson,:create_additions => false)['data']['edges'].sort.should == %w{one_two_pson two_three_pson}.sort
end
end
describe Puppet::Resource::Catalog, "when converting from pson", :if => Puppet.features.pson? do
def pson_result_should
Puppet::Resource::Catalog.expects(:new).with { |hash| yield hash }
end
before do
@data = {
'name' => "myhost"
}
@pson = {
'document_type' => 'Puppet::Resource::Catalog',
'data' => @data,
'metadata' => {}
}
@catalog = Puppet::Resource::Catalog.new("myhost")
Puppet::Resource::Catalog.stubs(:new).returns @catalog
end
it "should be extended with the PSON utility module" do
Puppet::Resource::Catalog.singleton_class.ancestors.should be_include(Puppet::Util::Pson)
end
it "should create it with the provided name" do
Puppet::Resource::Catalog.expects(:new).with('myhost').returns @catalog
PSON.parse @pson.to_pson
end
it "should set the provided version on the catalog if one is set" do
@data['version'] = 50
PSON.parse @pson.to_pson
@catalog.version.should == @data['version']
end
it "should set any provided tags on the catalog" do
@data['tags'] = %w{one two}
PSON.parse @pson.to_pson
@catalog.tags.should == @data['tags']
end
it "should set any provided classes on the catalog" do
@data['classes'] = %w{one two}
PSON.parse @pson.to_pson
@catalog.classes.should == @data['classes']
end
it 'should convert the resources list into resources and add each of them' do
@data['resources'] = [Puppet::Resource.new(:file, "/foo"), Puppet::Resource.new(:file, "/bar")]
@catalog.expects(:add_resource).times(2).with { |res| res.type == "File" }
PSON.parse @pson.to_pson
end
it 'should convert resources even if they do not include "type" information' do
@data['resources'] = [Puppet::Resource.new(:file, "/foo")]
@data['resources'][0].expects(:to_pson).returns '{"title":"/foo","tags":["file"],"type":"File"}'
@catalog.expects(:add_resource).with { |res| res.type == "File" }
PSON.parse @pson.to_pson
end
it 'should convert the edges list into edges and add each of them' do
one = Puppet::Relationship.new("osource", "otarget", :event => "one", :callback => "refresh")
two = Puppet::Relationship.new("tsource", "ttarget", :event => "two", :callback => "refresh")
@data['edges'] = [one, two]
@catalog.stubs(:resource).returns("eh")
@catalog.expects(:add_edge).with { |edge| edge.event == "one" }
@catalog.expects(:add_edge).with { |edge| edge.event == "two" }
PSON.parse @pson.to_pson
end
it "should be able to convert relationships that do not include 'type' information" do
one = Puppet::Relationship.new("osource", "otarget", :event => "one", :callback => "refresh")
one.expects(:to_pson).returns "{\"event\":\"one\",\"callback\":\"refresh\",\"source\":\"osource\",\"target\":\"otarget\"}"
@data['edges'] = [one]
@catalog.stubs(:resource).returns("eh")
@catalog.expects(:add_edge).with { |edge| edge.event == "one" }
PSON.parse @pson.to_pson
end
it "should set the source and target for each edge to the actual resource" do
edge = Puppet::Relationship.new("source", "target")
@data['edges'] = [edge]
@catalog.expects(:resource).with("source").returns("source_resource")
@catalog.expects(:resource).with("target").returns("target_resource")
@catalog.expects(:add_edge).with { |edge| edge.source == "source_resource" and edge.target == "target_resource" }
PSON.parse @pson.to_pson
end
it "should fail if the source resource cannot be found" do
edge = Puppet::Relationship.new("source", "target")
@data['edges'] = [edge]
@catalog.expects(:resource).with("source").returns(nil)
@catalog.stubs(:resource).with("target").returns("target_resource")
lambda { PSON.parse @pson.to_pson }.should raise_error(ArgumentError)
end
it "should fail if the target resource cannot be found" do
edge = Puppet::Relationship.new("source", "target")
@data['edges'] = [edge]
@catalog.stubs(:resource).with("source").returns("source_resource")
@catalog.expects(:resource).with("target").returns(nil)
lambda { PSON.parse @pson.to_pson }.should raise_error(ArgumentError)
end
describe "#title_key_for_ref" do
it "should parse a resource ref string into a pair" do
@catalog.title_key_for_ref("Title[name]").should == ["Title", "name"]
end
it "should parse a resource ref string into a pair, even if there's a newline inside the name" do
@catalog.title_key_for_ref("Title[na\nme]").should == ["Title", "na\nme"]
end
end
end
| 34.818841 | 211 | 0.656519 |
ede45edb097c8ea7ee7e2fe431580dda7f0109be | 2,281 | require "spec_helper"
require "active_attr/chainable_initialization"
require "active_support/concern"
module ActiveAttr
describe ChainableInitialization do
subject(:model) { model_class.new("arg") }
shared_examples "chained initialization" do
describe "#initialize" do
it { expect { model }.not_to raise_error }
it { model.initialized?.should == true }
end
end
context "mixed into a class with an argument to initialize" do
let :model_class do
Class.new do
include InitializationVerifier
include ChainableInitialization
def initialize(arg)
super
end
end
end
include_examples "chained initialization"
end
context "mixed into a subclass with an argument to initialize on the superclass" do
context "subclassing a model" do
let :parent_class do
Class.new do
include InitializationVerifier
def initialize(arg)
super
end
end
end
let :model_class do
Class.new(parent_class) do
include ChainableInitialization
def initialize(arg)
super
end
end
end
include_examples "chained initialization"
end
end
context "mixed into a concern which is mixed into a class with an argument to initialize" do
let :model_class do
Class.new do
include InitializationVerifier
include Module.new {
extend ActiveSupport::Concern
include ChainableInitialization
}
def initialize(arg)
super
end
end
end
include_examples "chained initialization"
end
if defined?(BasicObject) && BasicObject.superclass.nil?
context "mixed into a class that inherits from BasicObject with an argument to initialize" do
let :model_class do
Class.new(BasicObject) do
include InitializationVerifier
include ChainableInitialization
def initialize(arg)
super
end
end
end
include_examples "chained initialization"
end
end
end
end
| 24.265957 | 99 | 0.605436 |
ab4ed48e1702c1b68f80bf05dd8bc072b1361a90 | 247 | maintainer "Opscode"
maintainer_email "[email protected]"
license "Apache 2.0"
description "Installs/Configures template"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))
version "0.1"
| 35.285714 | 74 | 0.708502 |
e2181ffd5bfe378750f5c553e3aff0cc66dfeea7 | 1,422 | #!/usr/bin/env ruby
module Daily
class Configuration
def initialize()
@configs = nil
found = false
["~/.config/daily_brefing/config.json"].each { |item|
path = File.expand_path item
if File.exist? path
file = File.read(path)
@configs = JSON.parse(file)
found = true
break
end
}
if @configs.nil?
@configs =
{
'segments'=>
[
{'name'=>"Calendar"},
{'name'=>"CountTo", 'opt'=>{'data'=>[{'date'=>"2018-12-25", 'title'=>"Christmas"},]}},
{'name'=>"Evil", 'opt'=>{subscription:100}},
{'name'=>"Rss", 'opt'=>{'url'=>"http://rss.cnn.com/rss/cnn_topstories.rss"}},
{'name'=>"News"},
{'name'=>"RandomQuote"},
{'name'=>"Traffic"},
{'name'=>"UList",'opt'=>{'url' => "http://thomascherry.name/wiki/UList_(Little_Printer)",:id => "example_list"}},
{'name'=>"Weather"},
{'name'=>"WikiToday"}
]
}
end
end
def get
@configs
end
end
end | 34.682927 | 137 | 0.363572 |
1cf8555ef701b930c1e5caa7bc3e50baa54460ca | 430 | Российские фосфористы победили американцев и дошли до финала турнира на Олимпийских играх.
Сборная России по фехтованию вышла в финал командного турнира на Олимпийских играх в Рио - де - Жанейро.
В полуфинале российские спортсмены избили американскую команду со счетом 45-41.
Финал пройдет в 12: 30, где россияне настроены взять на себя команду из Франции, которая выиграла полуфинальный матч против итальянцев со счетом 45 - 30.
| 86 | 153 | 0.823256 |
62a1290bfa0509e7a020949d017fe8a9e863f3f3 | 1,267 | class Fd < Formula
desc "Simple, fast and user-friendly alternative to find"
homepage "https://github.com/sharkdp/fd"
url "https://github.com/sharkdp/fd/archive/v8.2.1.tar.gz"
sha256 "429de7f04a41c5ee6579e07a251c72342cd9cf5b11e6355e861bb3fffa794157"
license "Apache-2.0"
head "https://github.com/sharkdp/fd.git"
bottle do
cellar :any_skip_relocation
sha256 "378bf3b71edf7c09a80cd8815bd068f6c2b8abaf2df149fc23f33f52acecc817" => :big_sur
sha256 "b50a503fc0bddc9c82d6ebc42198071160426ee6247c122f8fb81b1f9ecc4aeb" => :arm64_big_sur
sha256 "1fef32a7cd0c80f62343b4caf6a0979f89bacfa7434ed54ffede6adb85ace329" => :catalina
sha256 "160cdfc22b5d0ac9694ce8dd95f7e22a7bdc95f6d376344d15f924f9ef67149b" => :mojave
sha256 "ee51f7f61ee4e4792bd8ed756982a7595b348d30a98f497e0570234045134de9" => :x86_64_linux
end
depends_on "rust" => :build
def install
ENV["SHELL_COMPLETIONS_DIR"] = buildpath
system "cargo", "install", *std_cargo_args
man1.install "doc/fd.1"
bash_completion.install "fd.bash"
fish_completion.install "fd.fish"
zsh_completion.install "contrib/completion/_fd"
end
test do
touch "foo_file"
touch "test_file"
assert_equal "test_file", shell_output("#{bin}/fd test").chomp
end
end
| 36.2 | 95 | 0.771113 |
7a6ec8bc6ed684a1be70df1c36adfa95a184cd48 | 2,397 | #
# This module provides methods to diff two hash, patch and unpatch hash
#
module HashDiffSym
# Apply patch to object
#
# @param [Hash, Array] obj the object to be patched, can be an Array or a Hash
# @param [Array] changes e.g. [[ '+', 'a.b', '45' ], [ '-', 'a.c', '5' ], [ '~', 'a.x', '45', '63']]
# @param [Hash] options supports following keys:
# * :delimiter (String) ['.'] delimiter string for representing nested keys in changes array
#
# @return the object after patch
#
# @since 0.0.1
def self.patch!(obj, changes, options = {})
delimiter = options[:delimiter] || '.'
changes.each do |change|
parts = decode_property_path(change[1], delimiter)
last_part = parts.last
parent_node = node(obj, parts[0, parts.size-1])
if change[0] == '+'
if last_part.is_a?(Fixnum)
parent_node.insert(last_part, change[2])
else
parent_node[last_part] = change[2]
end
elsif change[0] == '-'
if last_part.is_a?(Fixnum)
parent_node.delete_at(last_part)
else
parent_node.delete(last_part)
end
elsif change[0] == '~'
parent_node[last_part] = change[3]
end
end
obj
end
# Unpatch an object
#
# @param [Hash, Array] obj the object to be unpatched, can be an Array or a Hash
# @param [Array] changes e.g. [[ '+', 'a.b', '45' ], [ '-', 'a.c', '5' ], [ '~', 'a.x', '45', '63']]
# @param [Hash] options supports following keys:
# * :delimiter (String) ['.'] delimiter string for representing nested keys in changes array
#
# @return the object after unpatch
#
# @since 0.0.1
def self.unpatch!(obj, changes, options = {})
delimiter = options[:delimiter] || '.'
changes.reverse_each do |change|
parts = decode_property_path(change[1], delimiter)
last_part = parts.last
parent_node = node(obj, parts[0, parts.size-1])
if change[0] == '+'
if last_part.is_a?(Fixnum)
parent_node.delete_at(last_part)
else
parent_node.delete(last_part)
end
elsif change[0] == '-'
if last_part.is_a?(Fixnum)
parent_node.insert(last_part, change[2])
else
parent_node[last_part] = change[2]
end
elsif change[0] == '~'
parent_node[last_part] = change[2]
end
end
obj
end
end
| 28.2 | 102 | 0.582395 |
5d252e116b2e012e030906e036f102d50d4b07c1 | 59,350 | require 'test/unit'
require 'tempfile'
require 'timeout'
require 'io/wait'
require_relative 'envutil'
require 'rbconfig'
class TestProcess < Test::Unit::TestCase
RUBY = EnvUtil.rubybin
def setup
Process.waitall
end
def teardown
Process.waitall
end
def windows?
self.class.windows?
end
def self.windows?
return /mswin|mingw|bccwin/ =~ RUBY_PLATFORM
end
def write_file(filename, content)
File.open(filename, "w") {|f|
f << content
}
end
def with_tmpchdir
Dir.mktmpdir {|d|
d = File.realpath(d)
Dir.chdir(d) {
yield d
}
}
end
def run_in_child(str) # should be called in a temporary directory
write_file("test-script", str)
Process.wait spawn(RUBY, "test-script")
$?
end
def test_rlimit_availability
begin
Process.getrlimit(nil)
rescue NotImplementedError
assert_raise(NotImplementedError) { Process.setrlimit }
rescue TypeError
assert_raise(ArgumentError) { Process.setrlimit }
end
end
def rlimit_exist?
Process.getrlimit(nil)
rescue NotImplementedError
return false
rescue TypeError
return true
end
def test_rlimit_nofile
return unless rlimit_exist?
with_tmpchdir {
write_file 's', <<-"End"
# Too small RLIMIT_NOFILE, such as zero, causes problems.
# [OpenBSD] Setting to zero freezes this test.
# [GNU/Linux] EINVAL on poll(). EINVAL on ruby's internal poll() ruby with "[ASYNC BUG] thread_timer: select".
pipes = IO.pipe
limit = pipes.map {|io| io.fileno }.min
result = 1
begin
Process.setrlimit(Process::RLIMIT_NOFILE, limit)
rescue Errno::EINVAL
result = 0
end
if result == 1
begin
IO.pipe
rescue Errno::EMFILE
result = 0
end
end
exit result
End
pid = spawn RUBY, "s"
Process.wait pid
assert_equal(0, $?.to_i, "#{$?}")
}
end
def test_rlimit_name
return unless rlimit_exist?
[
:AS, "AS",
:CORE, "CORE",
:CPU, "CPU",
:DATA, "DATA",
:FSIZE, "FSIZE",
:MEMLOCK, "MEMLOCK",
:MSGQUEUE, "MSGQUEUE",
:NICE, "NICE",
:NOFILE, "NOFILE",
:NPROC, "NPROC",
:RSS, "RSS",
:RTPRIO, "RTPRIO",
:RTTIME, "RTTIME",
:SBSIZE, "SBSIZE",
:SIGPENDING, "SIGPENDING",
:STACK, "STACK",
].each {|name|
if Process.const_defined? "RLIMIT_#{name}"
assert_nothing_raised { Process.getrlimit(name) }
else
assert_raise(ArgumentError) { Process.getrlimit(name) }
end
}
assert_raise(ArgumentError) { Process.getrlimit(:FOO) }
assert_raise(ArgumentError) { Process.getrlimit("FOO") }
assert_raise_with_message(ArgumentError, /\u{30eb 30d3 30fc}/) { Process.getrlimit("\u{30eb 30d3 30fc}") }
end
def test_rlimit_value
return unless rlimit_exist?
assert_raise(ArgumentError) { Process.setrlimit(:FOO, 0) }
assert_raise(ArgumentError) { Process.setrlimit(:CORE, :FOO) }
assert_raise_with_message(ArgumentError, /\u{30eb 30d3 30fc}/) { Process.setrlimit("\u{30eb 30d3 30fc}", 0) }
assert_raise_with_message(ArgumentError, /\u{30eb 30d3 30fc}/) { Process.setrlimit(:CORE, "\u{30eb 30d3 30fc}") }
with_tmpchdir do
s = run_in_child(<<-'End')
cur, max = Process.getrlimit(:NOFILE)
Process.setrlimit(:NOFILE, [max-10, cur].min)
begin
Process.setrlimit(:NOFILE, :INFINITY)
rescue Errno::EPERM
exit false
end
End
assert_not_predicate(s, :success?)
s = run_in_child(<<-'End')
cur, max = Process.getrlimit(:NOFILE)
Process.setrlimit(:NOFILE, [max-10, cur].min)
begin
Process.setrlimit(:NOFILE, "INFINITY")
rescue Errno::EPERM
exit false
end
End
assert_not_predicate(s, :success?)
end
end
TRUECOMMAND = [RUBY, '-e', '']
def test_execopts_opts
assert_nothing_raised {
Process.wait Process.spawn(*TRUECOMMAND, {})
}
assert_raise(ArgumentError) {
Process.wait Process.spawn(*TRUECOMMAND, :foo => 100)
}
assert_raise(ArgumentError) {
Process.wait Process.spawn(*TRUECOMMAND, Process => 100)
}
end
def test_execopts_pgroup
skip "system(:pgroup) is not supported" if windows?
assert_nothing_raised { system(*TRUECOMMAND, :pgroup=>false) }
io = IO.popen([RUBY, "-e", "print Process.getpgrp"])
assert_equal(Process.getpgrp.to_s, io.read)
io.close
io = IO.popen([RUBY, "-e", "print Process.getpgrp", :pgroup=>true])
assert_equal(io.pid.to_s, io.read)
io.close
assert_raise(ArgumentError) { system(*TRUECOMMAND, :pgroup=>-1) }
assert_raise(Errno::EPERM) { Process.wait spawn(*TRUECOMMAND, :pgroup=>2) }
io1 = IO.popen([RUBY, "-e", "print Process.getpgrp", :pgroup=>true])
io2 = IO.popen([RUBY, "-e", "print Process.getpgrp", :pgroup=>io1.pid])
assert_equal(io1.pid.to_s, io1.read)
assert_equal(io1.pid.to_s, io2.read)
Process.wait io1.pid
Process.wait io2.pid
io1.close
io2.close
end
def test_execopts_rlimit
return unless rlimit_exist?
assert_raise(ArgumentError) { system(*TRUECOMMAND, :rlimit_foo=>0) }
assert_raise(ArgumentError) { system(*TRUECOMMAND, :rlimit_NOFILE=>0) }
assert_raise(ArgumentError) { system(*TRUECOMMAND, :rlimit_nofile=>[]) }
assert_raise(ArgumentError) { system(*TRUECOMMAND, :rlimit_nofile=>[1,2,3]) }
max = Process.getrlimit(:CORE).last
n = max
IO.popen([RUBY, "-e",
"p Process.getrlimit(:CORE)", :rlimit_core=>n]) {|io|
assert_equal("[#{n}, #{n}]\n", io.read)
}
n = 0
IO.popen([RUBY, "-e",
"p Process.getrlimit(:CORE)", :rlimit_core=>n]) {|io|
assert_equal("[#{n}, #{n}]\n", io.read)
}
n = max
IO.popen([RUBY, "-e",
"p Process.getrlimit(:CORE)", :rlimit_core=>[n]]) {|io|
assert_equal("[#{n}, #{n}]", io.read.chomp)
}
m, n = 0, max
IO.popen([RUBY, "-e",
"p Process.getrlimit(:CORE)", :rlimit_core=>[m,n]]) {|io|
assert_equal("[#{m}, #{n}]", io.read.chomp)
}
m, n = 0, 0
IO.popen([RUBY, "-e",
"p Process.getrlimit(:CORE)", :rlimit_core=>[m,n]]) {|io|
assert_equal("[#{m}, #{n}]", io.read.chomp)
}
n = max
IO.popen([RUBY, "-e",
"p Process.getrlimit(:CORE), Process.getrlimit(:CPU)",
:rlimit_core=>n, :rlimit_cpu=>3600]) {|io|
assert_equal("[#{n}, #{n}]\n[3600, 3600]", io.read.chomp)
}
end
MANDATORY_ENVS = %w[RUBYLIB]
case RbConfig::CONFIG['target_os']
when /linux/
MANDATORY_ENVS << 'LD_PRELOAD'
when /mswin|mingw/
MANDATORY_ENVS.concat(%w[HOME USER TMPDIR])
when /darwin/
MANDATORY_ENVS.concat(ENV.keys.grep(/\A__CF_/))
end
if e = RbConfig::CONFIG['LIBPATHENV']
MANDATORY_ENVS << e
end
PREENVARG = ['-e', "%w[#{MANDATORY_ENVS.join(' ')}].each{|e|ENV.delete(e)}"]
ENVARG = ['-e', 'ENV.each {|k,v| puts "#{k}=#{v}" }']
ENVCOMMAND = [RUBY].concat(PREENVARG).concat(ENVARG)
def test_execopts_env
assert_raise(ArgumentError) {
system({"F=O"=>"BAR"}, *TRUECOMMAND)
}
with_tmpchdir {|d|
prog = "#{d}/notexist"
e = assert_raise(Errno::ENOENT) {
Process.wait Process.spawn({"FOO"=>"BAR"}, prog)
}
assert_equal(prog, e.message.sub(/.* - /, ''))
e = assert_raise(Errno::ENOENT) {
Process.wait Process.spawn({"FOO"=>"BAR"}, [prog, "blar"])
}
assert_equal(prog, e.message.sub(/.* - /, ''))
}
h = {}
cmd = [h, RUBY]
(ENV.keys + MANDATORY_ENVS).each do |k|
case k
when /\APATH\z/i
when *MANDATORY_ENVS
cmd << '-e' << "ENV.delete('#{k}')"
else
h[k] = nil
end
end
cmd << '-e' << 'puts ENV.keys.map{|e|e.upcase}'
IO.popen(cmd) {|io|
assert_equal("PATH\n", io.read)
}
IO.popen([{"FOO"=>"BAR"}, *ENVCOMMAND]) {|io|
assert_match(/^FOO=BAR$/, io.read)
}
with_tmpchdir {|d|
system({"fofo"=>"haha"}, *ENVCOMMAND, STDOUT=>"out")
assert_match(/^fofo=haha$/, File.read("out").chomp)
}
old = ENV["hmm"]
begin
ENV["hmm"] = "fufu"
IO.popen(ENVCOMMAND) {|io| assert_match(/^hmm=fufu$/, io.read) }
IO.popen([{"hmm"=>""}, *ENVCOMMAND]) {|io| assert_match(/^hmm=$/, io.read) }
IO.popen([{"hmm"=>nil}, *ENVCOMMAND]) {|io| assert_not_match(/^hmm=/, io.read) }
ENV["hmm"] = ""
IO.popen(ENVCOMMAND) {|io| assert_match(/^hmm=$/, io.read) }
IO.popen([{"hmm"=>""}, *ENVCOMMAND]) {|io| assert_match(/^hmm=$/, io.read) }
IO.popen([{"hmm"=>nil}, *ENVCOMMAND]) {|io| assert_not_match(/^hmm=/, io.read) }
ENV["hmm"] = nil
IO.popen(ENVCOMMAND) {|io| assert_not_match(/^hmm=/, io.read) }
IO.popen([{"hmm"=>""}, *ENVCOMMAND]) {|io| assert_match(/^hmm=$/, io.read) }
IO.popen([{"hmm"=>nil}, *ENVCOMMAND]) {|io| assert_not_match(/^hmm=/, io.read) }
ensure
ENV["hmm"] = old
end
end
def _test_execopts_env_popen(cmd)
message = cmd.inspect
IO.popen({"FOO"=>"BAR"}, cmd) {|io|
assert_equal('FOO=BAR', io.read[/^FOO=.*/], message)
}
old = ENV["hmm"]
begin
ENV["hmm"] = "fufu"
IO.popen(cmd) {|io| assert_match(/^hmm=fufu$/, io.read, message)}
IO.popen({"hmm"=>""}, cmd) {|io| assert_match(/^hmm=$/, io.read, message)}
IO.popen({"hmm"=>nil}, cmd) {|io| assert_not_match(/^hmm=/, io.read, message)}
ENV["hmm"] = ""
IO.popen(cmd) {|io| assert_match(/^hmm=$/, io.read, message)}
IO.popen({"hmm"=>""}, cmd) {|io| assert_match(/^hmm=$/, io.read, message)}
IO.popen({"hmm"=>nil}, cmd) {|io| assert_not_match(/^hmm=/, io.read, message)}
ENV["hmm"] = nil
IO.popen(cmd) {|io| assert_not_match(/^hmm=/, io.read, message)}
IO.popen({"hmm"=>""}, cmd) {|io| assert_match(/^hmm=$/, io.read, message)}
IO.popen({"hmm"=>nil}, cmd) {|io| assert_not_match(/^hmm=/, io.read, message)}
ensure
ENV["hmm"] = old
end
end
def test_execopts_env_popen_vector
_test_execopts_env_popen(ENVCOMMAND)
end
def test_execopts_env_popen_string
with_tmpchdir do |d|
open('test-script', 'w') do |f|
ENVCOMMAND.each_with_index do |cmd, i|
next if i.zero? or cmd == "-e"
f.puts cmd
end
end
_test_execopts_env_popen("#{RUBY} test-script")
end
end
def test_execopts_preserve_env_on_exec_failure
with_tmpchdir {|d|
write_file 's', <<-"End"
ENV["mgg"] = nil
prog = "./nonexistent"
begin
Process.exec({"mgg" => "mggoo"}, [prog, prog])
rescue Errno::ENOENT
end
open('out', 'w') {|f|
f.print ENV["mgg"].inspect
}
End
system(RUBY, 's')
assert_equal(nil.inspect, File.read('out'),
"[ruby-core:44093] [ruby-trunk - Bug #6249]")
}
end
def test_execopts_env_single_word
with_tmpchdir {|d|
open("test_execopts_env_single_word.rb", "w") {|f|
f.puts "print ENV['hgga']"
}
system({"hgga"=>"ugu"}, RUBY,
:in => 'test_execopts_env_single_word.rb',
:out => 'test_execopts_env_single_word.out')
assert_equal('ugu', File.read('test_execopts_env_single_word.out'))
}
end
def test_execopts_unsetenv_others
h = {}
MANDATORY_ENVS.each {|k| e = ENV[k] and h[k] = e}
IO.popen([h, *ENVCOMMAND, :unsetenv_others=>true]) {|io|
assert_equal("", io.read)
}
IO.popen([h.merge("A"=>"B"), *ENVCOMMAND, :unsetenv_others=>true]) {|io|
assert_equal("A=B\n", io.read)
}
end
PWD = [RUBY, '-e', 'puts Dir.pwd']
def test_execopts_chdir
with_tmpchdir {|d|
IO.popen([*PWD, :chdir => d]) {|io|
assert_equal(d, io.read.chomp)
}
assert_raise(Errno::ENOENT) {
Process.wait Process.spawn(*PWD, :chdir => "d/notexist")
}
}
end
def test_execopts_open_chdir
with_tmpchdir {|d|
Dir.mkdir "foo"
system(*PWD, :chdir => "foo", :out => "open_chdir_test")
assert_file.exist?("open_chdir_test")
assert_file.not_exist?("foo/open_chdir_test")
assert_equal("#{d}/foo", File.read("open_chdir_test").chomp)
}
end
UMASK = [RUBY, '-e', 'printf "%04o\n", File.umask']
def test_execopts_umask
skip "umask is not supported" if windows?
IO.popen([*UMASK, :umask => 0]) {|io|
assert_equal("0000", io.read.chomp)
}
IO.popen([*UMASK, :umask => 0777]) {|io|
assert_equal("0777", io.read.chomp)
}
end
def with_pipe
begin
r, w = IO.pipe
yield r, w
ensure
r.close unless r.closed?
w.close unless w.closed?
end
end
def with_pipes(n)
ary = []
begin
n.times {
ary << IO.pipe
}
yield ary
ensure
ary.each {|r, w|
r.close unless r.closed?
w.close unless w.closed?
}
end
end
ECHO = lambda {|arg| [RUBY, '-e', "puts #{arg.dump}; STDOUT.flush"] }
SORT = [RUBY, '-e', "puts ARGF.readlines.sort"]
CAT = [RUBY, '-e', "IO.copy_stream STDIN, STDOUT"]
def test_execopts_redirect
with_tmpchdir {|d|
Process.wait Process.spawn(*ECHO["a"], STDOUT=>["out", File::WRONLY|File::CREAT|File::TRUNC, 0644])
assert_equal("a", File.read("out").chomp)
if windows?
# currently telling to child the file modes is not supported.
open("out", "a") {|f| f.write "0\n"}
else
Process.wait Process.spawn(*ECHO["0"], STDOUT=>["out", File::WRONLY|File::CREAT|File::APPEND, 0644])
assert_equal("a\n0\n", File.read("out"))
end
Process.wait Process.spawn(*SORT, STDIN=>["out", File::RDONLY, 0644],
STDOUT=>["out2", File::WRONLY|File::CREAT|File::TRUNC, 0644])
assert_equal("0\na\n", File.read("out2"))
Process.wait Process.spawn(*ECHO["b"], [STDOUT, STDERR]=>["out", File::WRONLY|File::CREAT|File::TRUNC, 0644])
assert_equal("b", File.read("out").chomp)
# problem occur with valgrind
#Process.wait Process.spawn(*ECHO["a"], STDOUT=>:close, STDERR=>["out", File::WRONLY|File::CREAT|File::TRUNC, 0644])
#p File.read("out")
#assert_not_empty(File.read("out")) # error message such as "-e:1:in `flush': Bad file descriptor (Errno::EBADF)"
Process.wait Process.spawn(*ECHO["c"], STDERR=>STDOUT, STDOUT=>["out", File::WRONLY|File::CREAT|File::TRUNC, 0644])
assert_equal("c", File.read("out").chomp)
File.open("out", "w") {|f|
Process.wait Process.spawn(*ECHO["d"], STDOUT=>f)
assert_equal("d", File.read("out").chomp)
}
opts = {STDOUT=>["out", File::WRONLY|File::CREAT|File::TRUNC, 0644]}
opts.merge(3=>STDOUT, 4=>STDOUT, 5=>STDOUT, 6=>STDOUT, 7=>STDOUT) unless windows?
Process.wait Process.spawn(*ECHO["e"], opts)
assert_equal("e", File.read("out").chomp)
opts = {STDOUT=>["out", File::WRONLY|File::CREAT|File::TRUNC, 0644]}
opts.merge(3=>0, 4=>:in, 5=>STDIN, 6=>1, 7=>:out, 8=>STDOUT, 9=>2, 10=>:err, 11=>STDERR) unless windows?
Process.wait Process.spawn(*ECHO["ee"], opts)
assert_equal("ee", File.read("out").chomp)
unless windows?
# passing non-stdio fds is not supported on Windows
File.open("out", "w") {|f|
h = {STDOUT=>f, f=>STDOUT}
3.upto(30) {|i| h[i] = STDOUT if f.fileno != i }
Process.wait Process.spawn(*ECHO["f"], h)
assert_equal("f", File.read("out").chomp)
}
end
assert_raise(ArgumentError) {
Process.wait Process.spawn(*ECHO["f"], 1=>Process)
}
assert_raise(ArgumentError) {
Process.wait Process.spawn(*ECHO["f"], [Process]=>1)
}
assert_raise(ArgumentError) {
Process.wait Process.spawn(*ECHO["f"], [1, STDOUT]=>2)
}
assert_raise(ArgumentError) {
Process.wait Process.spawn(*ECHO["f"], -1=>2)
}
Process.wait Process.spawn(*ECHO["hhh\nggg\n"], STDOUT=>"out")
assert_equal("hhh\nggg\n", File.read("out"))
Process.wait Process.spawn(*SORT, STDIN=>"out", STDOUT=>"out2")
assert_equal("ggg\nhhh\n", File.read("out2"))
unless windows?
# passing non-stdio fds is not supported on Windows
assert_raise(Errno::ENOENT) {
Process.wait Process.spawn("non-existing-command", (3..60).to_a=>["err", File::WRONLY|File::CREAT])
}
assert_equal("", File.read("err"))
end
system(*ECHO["bb\naa\n"], STDOUT=>["out", "w"])
assert_equal("bb\naa\n", File.read("out"))
system(*SORT, STDIN=>["out"], STDOUT=>"out2")
assert_equal("aa\nbb\n", File.read("out2"))
with_pipe {|r1, w1|
with_pipe {|r2, w2|
opts = {STDIN=>r1, STDOUT=>w2}
opts.merge(w1=>:close, r2=>:close) unless windows?
pid = spawn(*SORT, opts)
r1.close
w2.close
w1.puts "c"
w1.puts "a"
w1.puts "b"
w1.close
assert_equal("a\nb\nc\n", r2.read)
r2.close
Process.wait(pid)
}
}
unless windows?
# passing non-stdio fds is not supported on Windows
with_pipes(5) {|pipes|
ios = pipes.flatten
h = {}
ios.length.times {|i| h[ios[i]] = ios[(i-1)%ios.length] }
h2 = h.invert
_rios = pipes.map {|r, w| r }
wios = pipes.map {|r, w| w }
child_wfds = wios.map {|w| h2[w].fileno }
pid = spawn(RUBY, "-e",
"[#{child_wfds.join(',')}].each {|fd| IO.new(fd, 'w').puts fd }", h)
pipes.each {|r, w|
assert_equal("#{h2[w].fileno}\n", r.gets)
}
Process.wait pid;
}
with_pipes(5) {|pipes|
ios = pipes.flatten
h = {}
ios.length.times {|i| h[ios[i]] = ios[(i+1)%ios.length] }
h2 = h.invert
_rios = pipes.map {|r, w| r }
wios = pipes.map {|r, w| w }
child_wfds = wios.map {|w| h2[w].fileno }
pid = spawn(RUBY, "-e",
"[#{child_wfds.join(',')}].each {|fd| IO.new(fd, 'w').puts fd }", h)
pipes.each {|r, w|
assert_equal("#{h2[w].fileno}\n", r.gets)
}
Process.wait pid
}
closed_fd = nil
with_pipes(5) {|pipes|
io = pipes.last.last
closed_fd = io.fileno
}
assert_raise(Errno::EBADF) { Process.wait spawn(*TRUECOMMAND, closed_fd=>closed_fd) }
with_pipe {|r, w|
if w.respond_to?(:"close_on_exec=")
w.close_on_exec = true
pid = spawn(RUBY, "-e", "IO.new(#{w.fileno}, 'w').print 'a'", w=>w)
w.close
assert_equal("a", r.read)
Process.wait pid
end
}
end
system(*ECHO["funya"], :out=>"out")
assert_equal("funya\n", File.read("out"))
system(RUBY, '-e', 'STDOUT.reopen(STDERR); puts "henya"', :err=>"out")
assert_equal("henya\n", File.read("out"))
IO.popen([*CAT, :in=>"out"]) {|io|
assert_equal("henya\n", io.read)
}
}
end
def test_execopts_redirect_nonascii_path
bug9946 = '[ruby-core:63185] [Bug #9946]'
with_tmpchdir {|d|
path = "t-\u{30c6 30b9 30c8 f6}.txt"
system(*ECHO["a"], out: path)
assert_file.for(bug9946).exist?(path)
assert_equal("a\n", File.read(path), bug9946)
}
end
def test_execopts_redirect_to_out_and_err
with_tmpchdir {|d|
ret = system(RUBY, "-e", 'STDERR.print "e"; STDOUT.print "o"', [:out, :err] => "foo")
assert_equal(true, ret)
assert_equal("eo", File.read("foo"))
ret = system(RUBY, "-e", 'STDERR.print "E"; STDOUT.print "O"', [:err, :out] => "bar")
assert_equal(true, ret)
assert_equal("EO", File.read("bar"))
}
end
def test_execopts_redirect_dup2_child
with_tmpchdir {|d|
Process.wait spawn(RUBY, "-e", "STDERR.print 'err'; STDOUT.print 'out'",
STDOUT=>"out", STDERR=>[:child, STDOUT])
assert_equal("errout", File.read("out"))
Process.wait spawn(RUBY, "-e", "STDERR.print 'err'; STDOUT.print 'out'",
STDERR=>"out", STDOUT=>[:child, STDERR])
assert_equal("errout", File.read("out"))
skip "inheritance of fd other than stdin,stdout and stderr is not supported" if windows?
Process.wait spawn(RUBY, "-e", "STDERR.print 'err'; STDOUT.print 'out'",
STDOUT=>"out",
STDERR=>[:child, 3],
3=>[:child, 4],
4=>[:child, STDOUT]
)
assert_equal("errout", File.read("out"))
IO.popen([RUBY, "-e", "STDERR.print 'err'; STDOUT.print 'out'", STDERR=>[:child, STDOUT]]) {|io|
assert_equal("errout", io.read)
}
assert_raise(ArgumentError) { Process.wait spawn(*TRUECOMMAND, STDOUT=>[:child, STDOUT]) }
assert_raise(ArgumentError) { Process.wait spawn(*TRUECOMMAND, 3=>[:child, 4], 4=>[:child, 3]) }
assert_raise(ArgumentError) { Process.wait spawn(*TRUECOMMAND, 3=>[:child, 4], 4=>[:child, 5], 5=>[:child, 3]) }
assert_raise(ArgumentError) { Process.wait spawn(*TRUECOMMAND, STDOUT=>[:child, 3]) }
}
end
def test_execopts_exec
with_tmpchdir {|d|
write_file("s", 'exec "echo aaa", STDOUT=>"foo"')
pid = spawn RUBY, 's'
Process.wait pid
assert_equal("aaa\n", File.read("foo"))
}
end
def test_execopts_popen
with_tmpchdir {|d|
IO.popen("#{RUBY} -e 'puts :foo'") {|io| assert_equal("foo\n", io.read) }
assert_raise(Errno::ENOENT) { IO.popen(["echo bar"]) {} } # assuming "echo bar" command not exist.
IO.popen(ECHO["baz"]) {|io| assert_equal("baz\n", io.read) }
assert_raise(ArgumentError) {
IO.popen([*ECHO["qux"], STDOUT=>STDOUT]) {|io| }
}
IO.popen([*ECHO["hoge"], STDERR=>STDOUT]) {|io|
assert_equal("hoge\n", io.read)
}
assert_raise(ArgumentError) {
IO.popen([*ECHO["fuga"], STDOUT=>"out"]) {|io| }
}
skip "inheritance of fd other than stdin,stdout and stderr is not supported" if windows?
with_pipe {|r, w|
IO.popen([RUBY, '-e', 'IO.new(3, "w").puts("a"); puts "b"', 3=>w]) {|io|
assert_equal("b\n", io.read)
}
w.close
assert_equal("a\n", r.read)
}
IO.popen([RUBY, '-e', "IO.new(9, 'w').puts(:b)",
9=>["out2", File::WRONLY|File::CREAT|File::TRUNC]]) {|io|
assert_equal("", io.read)
}
assert_equal("b\n", File.read("out2"))
}
end
def test_popen_fork
IO.popen("-") {|io|
if !io
puts "fooo"
else
assert_equal("fooo\n", io.read)
end
}
rescue NotImplementedError
end
def test_fd_inheritance
skip "inheritance of fd other than stdin,stdout and stderr is not supported" if windows?
with_pipe {|r, w|
system(RUBY, '-e', 'IO.new(ARGV[0].to_i, "w").puts(:ba)', w.fileno.to_s, w=>w)
w.close
assert_equal("ba\n", r.read)
}
with_pipe {|r, w|
Process.wait spawn(RUBY, '-e',
'IO.new(ARGV[0].to_i, "w").puts("bi") rescue nil',
w.fileno.to_s)
w.close
assert_equal("", r.read)
}
with_pipe {|r, w|
with_tmpchdir {|d|
write_file("s", <<-"End")
exec(#{RUBY.dump}, '-e',
'IO.new(ARGV[0].to_i, "w").puts("bu") rescue nil',
#{w.fileno.to_s.dump}, :close_others=>false)
End
w.close_on_exec = false
Process.wait spawn(RUBY, "s", :close_others=>false)
w.close
assert_equal("bu\n", r.read)
}
}
with_pipe {|r, w|
io = IO.popen([RUBY, "-e", "STDERR.reopen(STDOUT); IO.new(#{w.fileno}, 'w').puts('me')"])
begin
w.close
errmsg = io.read
assert_equal("", r.read)
assert_not_equal("", errmsg)
ensure
io.close
end
}
with_pipe {|r, w|
errmsg = `#{RUBY} -e "STDERR.reopen(STDOUT); IO.new(#{w.fileno}, 'w').puts(123)"`
w.close
assert_equal("", r.read)
assert_not_equal("", errmsg)
}
end
def test_execopts_close_others
skip "inheritance of fd other than stdin,stdout and stderr is not supported" if windows?
with_tmpchdir {|d|
with_pipe {|r, w|
system(RUBY, '-e', 'STDERR.reopen("err", "w"); IO.new(ARGV[0].to_i, "w").puts("ma")', w.fileno.to_s, :close_others=>true)
w.close
assert_equal("", r.read)
assert_not_equal("", File.read("err"))
File.unlink("err")
}
with_pipe {|r, w|
Process.wait spawn(RUBY, '-e', 'STDERR.reopen("err", "w"); IO.new(ARGV[0].to_i, "w").puts("mi")', w.fileno.to_s, :close_others=>true)
w.close
assert_equal("", r.read)
assert_not_equal("", File.read("err"))
File.unlink("err")
}
with_pipe {|r, w|
w.close_on_exec = false
Process.wait spawn(RUBY, '-e', 'IO.new(ARGV[0].to_i, "w").puts("bi")', w.fileno.to_s, :close_others=>false)
w.close
assert_equal("bi\n", r.read)
}
with_pipe {|r, w|
write_file("s", <<-"End")
exec(#{RUBY.dump}, '-e',
'STDERR.reopen("err", "w"); IO.new(ARGV[0].to_i, "w").puts("mu")',
#{w.fileno.to_s.dump},
:close_others=>true)
End
Process.wait spawn(RUBY, "s", :close_others=>false)
w.close
assert_equal("", r.read)
assert_not_equal("", File.read("err"))
File.unlink("err")
}
with_pipe {|r, w|
io = IO.popen([RUBY, "-e", "STDERR.reopen(STDOUT); IO.new(#{w.fileno}, 'w').puts('me')", :close_others=>true])
begin
w.close
errmsg = io.read
assert_equal("", r.read)
assert_not_equal("", errmsg)
ensure
io.close
end
}
with_pipe {|r, w|
w.close_on_exec = false
io = IO.popen([RUBY, "-e", "STDERR.reopen(STDOUT); IO.new(#{w.fileno}, 'w').puts('mo')", :close_others=>false])
begin
w.close
errmsg = io.read
assert_equal("mo\n", r.read)
assert_equal("", errmsg)
ensure
io.close
end
}
with_pipe {|r, w|
w.close_on_exec = false
io = IO.popen([RUBY, "-e", "STDERR.reopen(STDOUT); IO.new(#{w.fileno}, 'w').puts('mo')", :close_others=>nil])
begin
w.close
errmsg = io.read
assert_equal("mo\n", r.read)
assert_equal("", errmsg)
ensure
io.close
end
}
}
end
def test_execopts_redirect_self
begin
with_pipe {|r, w|
w << "haha\n"
w.close
r.close_on_exec = true
IO.popen([RUBY, "-e", "print IO.new(#{r.fileno}, 'r').read", r.fileno=>r.fileno, :close_others=>false]) {|io|
assert_equal("haha\n", io.read)
}
}
rescue NotImplementedError
skip "IO#close_on_exec= is not supported"
end
end
def test_execopts_redirect_tempfile
bug6269 = '[ruby-core:44181]'
Tempfile.create("execopts") do |tmp|
pid = assert_nothing_raised(ArgumentError, bug6269) do
break spawn(RUBY, "-e", "print $$", out: tmp)
end
Process.wait(pid)
tmp.rewind
assert_equal(pid.to_s, tmp.read)
end
end
def test_execopts_duplex_io
IO.popen("#{RUBY} -e ''", "r+") {|duplex|
assert_raise(ArgumentError) { system("#{RUBY} -e ''", duplex=>STDOUT) }
assert_raise(ArgumentError) { system("#{RUBY} -e ''", STDOUT=>duplex) }
}
end
def test_execopts_modification
h = {}
Process.wait spawn(*TRUECOMMAND, h)
assert_equal({}, h)
h = {}
system(*TRUECOMMAND, h)
assert_equal({}, h)
h = {}
io = IO.popen([*TRUECOMMAND, h])
io.close
assert_equal({}, h)
end
def test_system_noshell
str = "echo non existing command name which contains spaces"
assert_nil(system([str, str]))
end
def test_spawn_noshell
str = "echo non existing command name which contains spaces"
assert_raise(Errno::ENOENT) { spawn([str, str]) }
end
def test_popen_noshell
str = "echo non existing command name which contains spaces"
assert_raise(Errno::ENOENT) { IO.popen([str, str]) }
end
def test_exec_noshell
with_tmpchdir {|d|
write_file("s", <<-"End")
str = "echo non existing command name which contains spaces"
STDERR.reopen(STDOUT)
begin
exec [str, str]
rescue Errno::ENOENT
print "Errno::ENOENT success"
end
End
r = IO.popen([RUBY, "s", :close_others=>false], "r") {|f| f.read}
assert_equal("Errno::ENOENT success", r)
}
end
def test_system_wordsplit
with_tmpchdir {|d|
write_file("script", <<-'End')
File.open("result", "w") {|t| t << "haha pid=#{$$} ppid=#{Process.ppid}" }
exit 5
End
str = "#{RUBY} script"
ret = system(str)
status = $?
assert_equal(false, ret)
assert_predicate(status, :exited?)
assert_equal(5, status.exitstatus)
assert_equal("haha pid=#{status.pid} ppid=#{$$}", File.read("result"))
}
end
def test_spawn_wordsplit
with_tmpchdir {|d|
write_file("script", <<-'End')
File.open("result", "w") {|t| t << "hihi pid=#{$$} ppid=#{Process.ppid}" }
exit 6
End
str = "#{RUBY} script"
pid = spawn(str)
Process.wait pid
status = $?
assert_equal(pid, status.pid)
assert_predicate(status, :exited?)
assert_equal(6, status.exitstatus)
assert_equal("hihi pid=#{status.pid} ppid=#{$$}", File.read("result"))
}
end
def test_popen_wordsplit
with_tmpchdir {|d|
write_file("script", <<-'End')
print "fufu pid=#{$$} ppid=#{Process.ppid}"
exit 7
End
str = "#{RUBY} script"
io = IO.popen(str)
pid = io.pid
result = io.read
io.close
status = $?
assert_equal(pid, status.pid)
assert_predicate(status, :exited?)
assert_equal(7, status.exitstatus)
assert_equal("fufu pid=#{status.pid} ppid=#{$$}", result)
}
end
def test_popen_wordsplit_beginning_and_trailing_spaces
with_tmpchdir {|d|
write_file("script", <<-'End')
print "fufumm pid=#{$$} ppid=#{Process.ppid}"
exit 7
End
str = " #{RUBY} script "
io = IO.popen(str)
pid = io.pid
result = io.read
io.close
status = $?
assert_equal(pid, status.pid)
assert_predicate(status, :exited?)
assert_equal(7, status.exitstatus)
assert_equal("fufumm pid=#{status.pid} ppid=#{$$}", result)
}
end
def test_exec_wordsplit
with_tmpchdir {|d|
write_file("script", <<-'End')
File.open("result", "w") {|t|
if /mswin|bccwin|mingw/ =~ RUBY_PLATFORM
t << "hehe ppid=#{Process.ppid}"
else
t << "hehe pid=#{$$} ppid=#{Process.ppid}"
end
}
exit 6
End
write_file("s", <<-"End")
ruby = #{RUBY.dump}
exec "\#{ruby} script"
End
pid = spawn(RUBY, "s")
Process.wait pid
status = $?
assert_equal(pid, status.pid)
assert_predicate(status, :exited?)
assert_equal(6, status.exitstatus)
if windows?
expected = "hehe ppid=#{status.pid}"
else
expected = "hehe pid=#{status.pid} ppid=#{$$}"
end
assert_equal(expected, File.read("result"))
}
end
def test_system_shell
with_tmpchdir {|d|
write_file("script1", <<-'End')
File.open("result1", "w") {|t| t << "taka pid=#{$$} ppid=#{Process.ppid}" }
exit 7
End
write_file("script2", <<-'End')
File.open("result2", "w") {|t| t << "taki pid=#{$$} ppid=#{Process.ppid}" }
exit 8
End
ret = system("#{RUBY} script1 || #{RUBY} script2")
status = $?
assert_equal(false, ret)
assert_predicate(status, :exited?)
result1 = File.read("result1")
result2 = File.read("result2")
assert_match(/\Ataka pid=\d+ ppid=\d+\z/, result1)
assert_match(/\Ataki pid=\d+ ppid=\d+\z/, result2)
assert_not_equal(result1[/\d+/].to_i, status.pid)
if windows?
Dir.mkdir(path = "path with space")
write_file(bat = path + "/bat test.bat", "@echo %1>out")
system(bat, "foo 'bar'")
assert_equal(%["foo 'bar'"\n], File.read("out"), '[ruby-core:22960]')
system(%[#{bat.dump} "foo 'bar'"])
assert_equal(%["foo 'bar'"\n], File.read("out"), '[ruby-core:22960]')
end
}
end
def test_spawn_shell
with_tmpchdir {|d|
write_file("script1", <<-'End')
File.open("result1", "w") {|t| t << "taku pid=#{$$} ppid=#{Process.ppid}" }
exit 7
End
write_file("script2", <<-'End')
File.open("result2", "w") {|t| t << "take pid=#{$$} ppid=#{Process.ppid}" }
exit 8
End
pid = spawn("#{RUBY} script1 || #{RUBY} script2")
Process.wait pid
status = $?
assert_predicate(status, :exited?)
assert_not_predicate(status, :success?)
result1 = File.read("result1")
result2 = File.read("result2")
assert_match(/\Ataku pid=\d+ ppid=\d+\z/, result1)
assert_match(/\Atake pid=\d+ ppid=\d+\z/, result2)
assert_not_equal(result1[/\d+/].to_i, status.pid)
if windows?
Dir.mkdir(path = "path with space")
write_file(bat = path + "/bat test.bat", "@echo %1>out")
pid = spawn(bat, "foo 'bar'")
Process.wait pid
status = $?
assert_predicate(status, :exited?)
assert_predicate(status, :success?)
assert_equal(%["foo 'bar'"\n], File.read("out"), '[ruby-core:22960]')
pid = spawn(%[#{bat.dump} "foo 'bar'"])
Process.wait pid
status = $?
assert_predicate(status, :exited?)
assert_predicate(status, :success?)
assert_equal(%["foo 'bar'"\n], File.read("out"), '[ruby-core:22960]')
end
}
end
def test_popen_shell
with_tmpchdir {|d|
write_file("script1", <<-'End')
puts "tako pid=#{$$} ppid=#{Process.ppid}"
exit 7
End
write_file("script2", <<-'End')
puts "tika pid=#{$$} ppid=#{Process.ppid}"
exit 8
End
io = IO.popen("#{RUBY} script1 || #{RUBY} script2")
result = io.read
io.close
status = $?
assert_predicate(status, :exited?)
assert_not_predicate(status, :success?)
assert_match(/\Atako pid=\d+ ppid=\d+\ntika pid=\d+ ppid=\d+\n\z/, result)
assert_not_equal(result[/\d+/].to_i, status.pid)
if windows?
Dir.mkdir(path = "path with space")
write_file(bat = path + "/bat test.bat", "@echo %1")
r = IO.popen([bat, "foo 'bar'"]) {|f| f.read}
assert_equal(%["foo 'bar'"\n], r, '[ruby-core:22960]')
r = IO.popen(%[#{bat.dump} "foo 'bar'"]) {|f| f.read}
assert_equal(%["foo 'bar'"\n], r, '[ruby-core:22960]')
end
}
end
def test_exec_shell
with_tmpchdir {|d|
write_file("script1", <<-'End')
File.open("result1", "w") {|t| t << "tiki pid=#{$$} ppid=#{Process.ppid}" }
exit 7
End
write_file("script2", <<-'End')
File.open("result2", "w") {|t| t << "tiku pid=#{$$} ppid=#{Process.ppid}" }
exit 8
End
write_file("s", <<-"End")
ruby = #{RUBY.dump}
exec("\#{ruby} script1 || \#{ruby} script2")
End
pid = spawn RUBY, "s"
Process.wait pid
status = $?
assert_predicate(status, :exited?)
assert_not_predicate(status, :success?)
result1 = File.read("result1")
result2 = File.read("result2")
assert_match(/\Atiki pid=\d+ ppid=\d+\z/, result1)
assert_match(/\Atiku pid=\d+ ppid=\d+\z/, result2)
assert_not_equal(result1[/\d+/].to_i, status.pid)
}
end
def test_argv0
with_tmpchdir {|d|
assert_equal(false, system([RUBY, "asdfg"], "-e", "exit false"))
assert_equal(true, system([RUBY, "zxcvb"], "-e", "exit true"))
Process.wait spawn([RUBY, "poiu"], "-e", "exit 4")
assert_equal(4, $?.exitstatus)
assert_equal("1", IO.popen([[RUBY, "qwerty"], "-e", "print 1"]) {|f| f.read })
write_file("s", <<-"End")
exec([#{RUBY.dump}, "lkjh"], "-e", "exit 5")
End
pid = spawn RUBY, "s"
Process.wait pid
assert_equal(5, $?.exitstatus)
}
end
def with_stdin(filename)
open(filename) {|f|
begin
old = STDIN.dup
begin
STDIN.reopen(filename)
yield
ensure
STDIN.reopen(old)
end
ensure
old.close
end
}
end
def test_argv0_noarg
with_tmpchdir {|d|
open("t", "w") {|f| f.print "exit true" }
open("f", "w") {|f| f.print "exit false" }
with_stdin("t") { assert_equal(true, system([RUBY, "qaz"])) }
with_stdin("f") { assert_equal(false, system([RUBY, "wsx"])) }
with_stdin("t") { Process.wait spawn([RUBY, "edc"]) }
assert_predicate($?, :success?)
with_stdin("f") { Process.wait spawn([RUBY, "rfv"]) }
assert_not_predicate($?, :success?)
with_stdin("t") { IO.popen([[RUBY, "tgb"]]) {|io| assert_equal("", io.read) } }
assert_predicate($?, :success?)
with_stdin("f") { IO.popen([[RUBY, "yhn"]]) {|io| assert_equal("", io.read) } }
assert_not_predicate($?, :success?)
status = run_in_child "STDIN.reopen('t'); exec([#{RUBY.dump}, 'ujm'])"
assert_predicate(status, :success?)
status = run_in_child "STDIN.reopen('f'); exec([#{RUBY.dump}, 'ik,'])"
assert_not_predicate(status, :success?)
}
end
def test_status
with_tmpchdir do
s = run_in_child("exit 1")
assert_equal("#<Process::Status: pid #{ s.pid } exit #{ s.exitstatus }>", s.inspect)
assert_equal(s, s)
assert_equal(s, s.to_i)
assert_equal(s.to_i & 0x55555555, s & 0x55555555)
assert_equal(s.to_i >> 1, s >> 1)
assert_equal(false, s.stopped?)
assert_equal(nil, s.stopsig)
end
end
def test_status_kill
return unless Process.respond_to?(:kill)
return unless Signal.list.include?("KILL")
# assume the system supports signal if SIGQUIT is available
expected = Signal.list.include?("QUIT") ? [false, true, false, nil] : [true, false, false, true]
with_tmpchdir do
write_file("foo", "Process.kill(:KILL, $$); exit(42)")
system(RUBY, "foo")
s = $?
assert_equal(expected,
[s.exited?, s.signaled?, s.stopped?, s.success?],
"[s.exited?, s.signaled?, s.stopped?, s.success?]")
end
end
def test_status_quit
return unless Process.respond_to?(:kill)
return unless Signal.list.include?("QUIT")
with_tmpchdir do
write_file("foo", "puts;STDOUT.flush;sleep 30")
pid = nil
IO.pipe do |r, w|
pid = spawn(RUBY, "foo", out: w)
w.close
th = Thread.new { r.read(1); Process.kill(:SIGQUIT, pid) }
Process.wait(pid)
th.join
end
t = Time.now
s = $?
assert_equal([false, true, false, nil],
[s.exited?, s.signaled?, s.stopped?, s.success?],
"[s.exited?, s.signaled?, s.stopped?, s.success?]")
assert_send(
[["#<Process::Status: pid #{ s.pid } SIGQUIT (signal #{ s.termsig })>",
"#<Process::Status: pid #{ s.pid } SIGQUIT (signal #{ s.termsig }) (core dumped)>"],
:include?,
s.inspect])
EnvUtil.diagnostic_reports("QUIT", RUBY, pid, t)
end
end
def test_wait_without_arg
with_tmpchdir do
write_file("foo", "sleep 0.1")
pid = spawn(RUBY, "foo")
assert_equal(pid, Process.wait)
end
end
def test_wait2
with_tmpchdir do
write_file("foo", "sleep 0.1")
pid = spawn(RUBY, "foo")
assert_equal([pid, 0], Process.wait2)
end
end
def test_waitall
with_tmpchdir do
write_file("foo", "sleep 0.1")
ps = (0...3).map { spawn(RUBY, "foo") }.sort
ss = Process.waitall.sort
ps.zip(ss) do |p1, (p2, s)|
assert_equal(p1, p2)
assert_equal(p1, s.pid)
end
end
end
def test_abort
with_tmpchdir do
s = run_in_child("abort")
assert_not_equal(0, s.exitstatus)
end
end
def test_sleep
assert_raise(ArgumentError) { sleep(1, 1) }
end
def test_getpgid
assert_kind_of(Integer, Process.getpgid(Process.ppid))
rescue NotImplementedError
end
def test_getpriority
assert_kind_of(Integer, Process.getpriority(Process::PRIO_PROCESS, $$))
rescue NameError, NotImplementedError
end
def test_setpriority
if defined? Process::PRIO_USER
assert_nothing_raised do
pr = Process.getpriority(Process::PRIO_PROCESS, $$)
Process.setpriority(Process::PRIO_PROCESS, $$, pr)
end
end
end
def test_getuid
assert_kind_of(Integer, Process.uid)
end
def test_groups
gs = Process.groups
assert_instance_of(Array, gs)
gs.each {|g| assert_kind_of(Integer, g) }
rescue NotImplementedError
end
def test_maxgroups
assert_kind_of(Integer, Process.maxgroups)
rescue NotImplementedError
end
def test_geteuid
assert_kind_of(Integer, Process.euid)
end
def test_seteuid
assert_nothing_raised(TypeError) {Process.euid += 0}
rescue NotImplementedError
end
def test_seteuid_name
user = ENV["USER"] or return
assert_nothing_raised(TypeError) {Process.euid = user}
rescue NotImplementedError
end
def test_getegid
assert_kind_of(Integer, Process.egid)
end
def test_setegid
assert_nothing_raised(TypeError) {Process.egid += 0}
rescue NotImplementedError
end
def test_uid_re_exchangeable_p
r = Process::UID.re_exchangeable?
assert_include([true, false], r)
end
def test_gid_re_exchangeable_p
r = Process::GID.re_exchangeable?
assert_include([true, false], r)
end
def test_uid_sid_available?
r = Process::UID.sid_available?
assert_include([true, false], r)
end
def test_gid_sid_available?
r = Process::GID.sid_available?
assert_include([true, false], r)
end
def test_pst_inspect
assert_nothing_raised { Process::Status.allocate.inspect }
end
def test_wait_and_sigchild
if /freebsd|openbsd/ =~ RUBY_PLATFORM
# this relates #4173
# When ruby can use 2 cores, signal and wait4 may miss the signal.
skip "this fails on FreeBSD and OpenBSD on multithreaded environment"
end
signal_received = []
Signal.trap(:CHLD) { signal_received << true }
pid = nil
IO.pipe do |r, w|
pid = fork { r.read(1); exit }
Thread.start { raise }
w.puts
end
Process.wait pid
10.times do
break unless signal_received.empty?
sleep 0.01
end
assert_equal [true], signal_received, " [ruby-core:19744]"
rescue NotImplementedError, ArgumentError
ensure
begin
Signal.trap(:CHLD, 'DEFAULT')
rescue ArgumentError
end
end
def test_no_curdir
with_tmpchdir {|d|
Dir.mkdir("vd")
status = nil
Dir.chdir("vd") {
dir = "#{d}/vd"
# OpenSolaris cannot remove the current directory.
system(RUBY, "--disable-gems", "-e", "Dir.chdir '..'; Dir.rmdir #{dir.dump}", err: File::NULL)
system({"RUBYLIB"=>nil}, RUBY, "--disable-gems", "-e", "exit true")
status = $?
}
assert_predicate(status, :success?, "[ruby-dev:38105]")
}
end
def test_fallback_to_sh
feature = '[ruby-core:32745]'
with_tmpchdir do |d|
open("tmp_script.#{$$}", "w") {|f| f.puts ": ;"; f.chmod(0755)}
assert_not_nil(pid = Process.spawn("./tmp_script.#{$$}"), feature)
wpid, st = Process.waitpid2(pid)
assert_equal([pid, true], [wpid, st.success?], feature)
open("tmp_script.#{$$}", "w") {|f| f.puts "echo $#: $@"; f.chmod(0755)}
result = IO.popen(["./tmp_script.#{$$}", "a b", "c"]) {|f| f.read}
assert_equal("2: a b c\n", result, feature)
open("tmp_script.#{$$}", "w") {|f| f.puts "echo $hghg"; f.chmod(0755)}
result = IO.popen([{"hghg" => "mogomogo"}, "./tmp_script.#{$$}", "a b", "c"]) {|f| f.read}
assert_equal("mogomogo\n", result, feature)
end
end if File.executable?("/bin/sh")
def test_spawn_too_long_path
bug4314 = '[ruby-core:34842]'
assert_fail_too_long_path(%w"echo", bug4314)
end
def test_aspawn_too_long_path
bug4315 = '[ruby-core:34833]'
assert_fail_too_long_path(%w"echo |", bug4315)
end
def assert_fail_too_long_path((cmd, sep), mesg)
sep ||= ""
min = 1_000 / (cmd.size + sep.size)
cmds = Array.new(min, cmd)
exs = [Errno::ENOENT]
exs << Errno::E2BIG if defined?(Errno::E2BIG)
EnvUtil.suppress_warning do
assert_raise(*exs, mesg) do
begin
loop do
Process.spawn(cmds.join(sep), [STDOUT, STDERR]=>File::NULL)
min = [cmds.size, min].max
cmds *= 100
end
rescue NoMemoryError
size = cmds.size
raise if min >= size - 1
min = [min, size /= 2].max
cmds[size..-1] = []
raise if size < 250
retry
end
end
end
end
def test_system_sigpipe
return if windows?
pid = 0
with_tmpchdir do
assert_nothing_raised('[ruby-dev:12261]') do
timeout(3) do
pid = spawn('yes | ls')
Process.waitpid pid
end
end
end
ensure
Process.kill(:KILL, pid) if (pid != 0) rescue false
end
if Process.respond_to?(:daemon)
def test_daemon_default
data = IO.popen("-", "r+") do |f|
break f.read if f
Process.daemon
puts "ng"
end
assert_equal("", data)
end
def test_daemon_noclose
data = IO.popen("-", "r+") do |f|
break f.read if f
Process.daemon(false, true)
puts "ok", Dir.pwd
end
assert_equal("ok\n/\n", data)
end
def test_daemon_nochdir_noclose
data = IO.popen("-", "r+") do |f|
break f.read if f
Process.daemon(true, true)
puts "ok", Dir.pwd
end
assert_equal("ok\n#{Dir.pwd}\n", data)
end
def test_daemon_readwrite
data = IO.popen("-", "r+") do |f|
if f
f.puts "ok?"
break f.read
end
Process.daemon(true, true)
puts STDIN.gets
end
assert_equal("ok?\n", data)
end
def test_daemon_pid
cpid, dpid = IO.popen("-", "r+") do |f|
break f.pid, Integer(f.read) if f
Process.daemon(false, true)
puts $$
end
assert_not_equal(cpid, dpid)
end
if File.directory?("/proc/self/task") && /netbsd[a-z]*[1-6]/ !~ RUBY_PLATFORM
def test_daemon_no_threads
pid, data = IO.popen("-", "r+") do |f|
break f.pid, f.readlines if f
Process.daemon(true, true)
puts Dir.entries("/proc/self/task") - %W[. ..]
end
bug4920 = '[ruby-dev:43873]'
assert_equal(2, data.size, bug4920)
assert_not_include(data.map(&:to_i), pid)
end
else # darwin
def test_daemon_no_threads
data = Timeout.timeout(3) do
IO.popen("-") do |f|
break f.readlines.map(&:chomp) if f
th = Thread.start {sleep 3}
Process.daemon(true, true)
puts Thread.list.size, th.status.inspect
end
end
assert_equal(["1", "false"], data)
end
end
end
def test_popen_cloexec
return unless defined? Fcntl::FD_CLOEXEC
IO.popen([RUBY, "-e", ""]) {|io|
assert_predicate(io, :close_on_exec?)
}
end
def test_execopts_new_pgroup
return unless windows?
assert_nothing_raised { system(*TRUECOMMAND, :new_pgroup=>true) }
assert_nothing_raised { system(*TRUECOMMAND, :new_pgroup=>false) }
assert_nothing_raised { spawn(*TRUECOMMAND, :new_pgroup=>true) }
assert_nothing_raised { IO.popen([*TRUECOMMAND, :new_pgroup=>true]) {} }
end
def test_execopts_uid
feature6975 = '[ruby-core:47414]'
[30000, [Process.uid, ENV["USER"]]].each do |uid, user|
if user
assert_nothing_raised(feature6975) do
begin
system(*TRUECOMMAND, uid: user)
rescue Errno::EPERM, NotImplementedError
end
end
end
assert_nothing_raised(feature6975) do
begin
system(*TRUECOMMAND, uid: uid)
rescue Errno::EPERM, NotImplementedError
end
end
assert_nothing_raised(feature6975) do
begin
u = IO.popen([RUBY, "-e", "print Process.uid", uid: user||uid], &:read)
assert_equal(uid.to_s, u, feature6975)
rescue Errno::EPERM, NotImplementedError
end
end
end
end
def test_execopts_gid
skip "Process.groups not implemented on Windows platform" if windows?
feature6975 = '[ruby-core:47414]'
[30000, *Process.groups.map {|g| g = Etc.getgrgid(g); [g.name, g.gid]}].each do |group, gid|
assert_nothing_raised(feature6975) do
begin
system(*TRUECOMMAND, gid: group)
rescue Errno::EPERM, NotImplementedError
end
end
gid = "#{gid || group}"
assert_nothing_raised(feature6975) do
begin
g = IO.popen([RUBY, "-e", "print Process.gid", gid: group], &:read)
assert_equal(gid, g, feature6975)
rescue Errno::EPERM, NotImplementedError
end
end
end
end
def test_sigpipe
system(RUBY, "-e", "")
with_pipe {|r, w|
r.close
assert_raise(Errno::EPIPE) { w.print "a" }
}
end
def test_sh_comment
IO.popen("echo a # fofoof") {|f|
assert_equal("a\n", f.read)
}
end if File.executable?("/bin/sh")
def test_sh_env
IO.popen("foofoo=barbar env") {|f|
lines = f.readlines
assert_operator(lines, :include?, "foofoo=barbar\n")
}
end if File.executable?("/bin/sh")
def test_sh_exec
IO.popen("exec echo exexexec") {|f|
assert_equal("exexexec\n", f.read)
}
end if File.executable?("/bin/sh")
def test_setsid
return unless Process.respond_to?(:setsid)
return unless Process.respond_to?(:getsid)
# OpenBSD and AIX don't allow Process::getsid(pid) when pid is in
# different session.
return if /openbsd|aix/ =~ RUBY_PLATFORM
IO.popen([RUBY, "-e", <<EOS]) do|io|
Marshal.dump(Process.getsid, STDOUT)
newsid = Process.setsid
Marshal.dump(newsid, STDOUT)
STDOUT.flush
# getsid() on MacOS X return ESRCH when target process is zombie
# even if it is valid process id.
sleep
EOS
begin
# test Process.getsid() w/o arg
assert_equal(Marshal.load(io), Process.getsid)
# test Process.setsid return value and Process::getsid(pid)
assert_equal(Marshal.load(io), Process.getsid(io.pid))
ensure
Process.kill(:KILL, io.pid) rescue nil
Process.wait(io.pid)
end
end
end
def test_spawn_nonascii
bug1771 = '[ruby-core:24309] [Bug #1771]'
with_tmpchdir do
[
"\u{7d05 7389}",
"zuf\u{00E4}llige_\u{017E}lu\u{0165}ou\u{010D}k\u{00FD}_\u{10D2 10D0 10DB 10D4 10DD 10E0 10D4 10D1}_\u{0440 0430 0437 043B 043E 0433 0430}_\u{548C 65B0 52A0 5761 4EE5 53CA 4E1C}",
"c\u{1EE7}a",
].each do |name|
msg = "#{bug1771} #{name}"
exename = "./#{name}.exe"
FileUtils.cp(ENV["COMSPEC"], exename)
assert_equal(true, system("#{exename} /c exit"), msg)
system("#{exename} /c exit 12")
assert_equal(12, $?.exitstatus, msg)
_, status = Process.wait2(Process.spawn("#{exename} /c exit 42"))
assert_equal(42, status.exitstatus, msg)
assert_equal("ok\n", `#{exename} /c echo ok`, msg)
assert_equal("ok\n", IO.popen("#{exename} /c echo ok", &:read), msg)
assert_equal("ok\n", IO.popen(%W"#{exename} /c echo ok", &:read), msg)
File.binwrite("#{name}.txt", "ok")
assert_equal("ok", `type #{name}.txt`)
end
end
end if windows?
def test_clock_gettime
t1 = Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond)
t2 = Time.now; t2 = t2.tv_sec * 1000000000 + t2.tv_nsec
t3 = Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond)
assert_operator(t1, :<=, t2)
assert_operator(t2, :<=, t3)
assert_raise(Errno::EINVAL) { Process.clock_gettime(:foo) }
end
def test_clock_gettime_unit
t0 = Time.now.to_f
[
[:nanosecond, 1_000_000_000],
[:microsecond, 1_000_000],
[:millisecond, 1_000],
[:second, 1],
[:float_microsecond, 1_000_000.0],
[:float_millisecond, 1_000.0],
[:float_second, 1.0],
[nil, 1.0],
[:foo],
].each do |unit, num|
unless num
assert_raise(ArgumentError){ Process.clock_gettime(Process::CLOCK_REALTIME, unit) }
next
end
t1 = Process.clock_gettime(Process::CLOCK_REALTIME, unit)
assert_kind_of num.integer? ? Integer : num.class, t1, [unit, num].inspect
assert_in_delta t0, t1/num, 1, [unit, num].inspect
end
end
def test_clock_gettime_constants
Process.constants.grep(/\ACLOCK_/).each {|n|
c = Process.const_get(n)
begin
t = Process.clock_gettime(c)
rescue Errno::EINVAL
next
end
assert_kind_of(Float, t, "Process.clock_gettime(Process::#{n})")
}
end
def test_clock_gettime_GETTIMEOFDAY_BASED_CLOCK_REALTIME
n = :GETTIMEOFDAY_BASED_CLOCK_REALTIME
t = Process.clock_gettime(n)
assert_kind_of(Float, t, "Process.clock_gettime(:#{n})")
end
def test_clock_gettime_TIME_BASED_CLOCK_REALTIME
n = :TIME_BASED_CLOCK_REALTIME
t = Process.clock_gettime(n)
assert_kind_of(Float, t, "Process.clock_gettime(:#{n})")
end
def test_clock_gettime_TIMES_BASED_CLOCK_MONOTONIC
n = :TIMES_BASED_CLOCK_MONOTONIC
begin
t = Process.clock_gettime(n)
rescue Errno::EINVAL
return
end
assert_kind_of(Float, t, "Process.clock_gettime(:#{n})")
end
def test_clock_gettime_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID
n = :GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID
begin
t = Process.clock_gettime(n)
rescue Errno::EINVAL
return
end
assert_kind_of(Float, t, "Process.clock_gettime(:#{n})")
end
def test_clock_gettime_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID
n = :TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID
begin
t = Process.clock_gettime(n)
rescue Errno::EINVAL
return
end
assert_kind_of(Float, t, "Process.clock_gettime(:#{n})")
end
def test_clock_gettime_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID
n = :CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID
t = Process.clock_gettime(n)
assert_kind_of(Float, t, "Process.clock_gettime(:#{n})")
end
def test_clock_gettime_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC
n = :MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC
begin
t = Process.clock_gettime(n)
rescue Errno::EINVAL
return
end
assert_kind_of(Float, t, "Process.clock_gettime(:#{n})")
end
def test_clock_getres
r = Process.clock_getres(Process::CLOCK_REALTIME, :nanosecond)
rescue Errno::EINVAL
else
assert_kind_of(Integer, r)
assert_raise(Errno::EINVAL) { Process.clock_getres(:foo) }
end
def test_clock_getres_constants
Process.constants.grep(/\ACLOCK_/).each {|n|
c = Process.const_get(n)
begin
t = Process.clock_getres(c)
rescue Errno::EINVAL
next
end
assert_kind_of(Float, t, "Process.clock_getres(Process::#{n})")
}
end
def test_clock_getres_GETTIMEOFDAY_BASED_CLOCK_REALTIME
n = :GETTIMEOFDAY_BASED_CLOCK_REALTIME
t = Process.clock_getres(n)
assert_kind_of(Float, t, "Process.clock_getres(:#{n})")
assert_equal(1000, Process.clock_getres(n, :nanosecond))
end
def test_clock_getres_TIME_BASED_CLOCK_REALTIME
n = :TIME_BASED_CLOCK_REALTIME
t = Process.clock_getres(n)
assert_kind_of(Float, t, "Process.clock_getres(:#{n})")
assert_equal(1000000000, Process.clock_getres(n, :nanosecond))
end
def test_clock_getres_TIMES_BASED_CLOCK_MONOTONIC
n = :TIMES_BASED_CLOCK_MONOTONIC
begin
t = Process.clock_getres(n)
rescue Errno::EINVAL
return
end
assert_kind_of(Float, t, "Process.clock_getres(:#{n})")
f = Process.clock_getres(n, :hertz)
assert_equal(0, f - f.floor)
end
def test_clock_getres_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID
n = :GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID
begin
t = Process.clock_getres(n)
rescue Errno::EINVAL
return
end
assert_kind_of(Float, t, "Process.clock_getres(:#{n})")
assert_equal(1000, Process.clock_getres(n, :nanosecond))
end
def test_clock_getres_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID
n = :TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID
begin
t = Process.clock_getres(n)
rescue Errno::EINVAL
return
end
assert_kind_of(Float, t, "Process.clock_getres(:#{n})")
f = Process.clock_getres(n, :hertz)
assert_equal(0, f - f.floor)
end
def test_clock_getres_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID
n = :CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID
t = Process.clock_getres(n)
assert_kind_of(Float, t, "Process.clock_getres(:#{n})")
f = Process.clock_getres(n, :hertz)
assert_equal(0, f - f.floor)
end
def test_clock_getres_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC
n = :MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC
begin
t = Process.clock_getres(n)
rescue Errno::EINVAL
return
end
assert_kind_of(Float, t, "Process.clock_getres(:#{n})")
end
def test_deadlock_by_signal_at_forking
GC.start # reduce garbage
buf = ''
ruby = EnvUtil.rubybin
er, ew = IO.pipe
unless runner = IO.popen("-".freeze)
er.close
status = true
GC.disable # avoid triggering CoW after forks
begin
$stderr.reopen($stdout)
trap(:QUIT) {}
parent = $$
100.times do |i|
pid = fork {Process.kill(:QUIT, parent)}
IO.popen(ruby, 'r+'.freeze){}
Process.wait(pid)
$stdout.puts
$stdout.flush
end
ensure
if $!
ew.puts([Marshal.dump($!)].pack("m0"))
status = false
end
ew.close
exit!(status)
end
end
ew.close
begin
loop do
runner.wait_readable(5)
runner.read_nonblock(100, buf)
end
rescue EOFError => e
_, status = Process.wait2(runner.pid)
rescue IO::WaitReadable => e
Process.kill(:INT, runner.pid)
raise Marshal.load(er.read.unpack("m")[0])
end
assert_predicate(status, :success?)
ensure
er.close unless er.closed?
ew.close unless ew.closed?
if runner
begin
Process.kill(:TERM, runner.pid)
sleep 1
Process.kill(:KILL, runner.pid)
rescue Errno::ESRCH
end
runner.close
end
end if defined?(fork)
def test_process_detach
pid = fork {}
th = Process.detach(pid)
assert_equal pid, th.pid
status = th.value
assert status.success?, status.inspect
end if defined?(fork)
end
| 29.899244 | 186 | 0.583589 |
f7cf16f5bdd8ac2ef27c3ca138b9f7c8ba6eb575 | 75 | # frozen_string_literal: true
module TencentCloud
VERSION = '0.3.5'
end
| 12.5 | 29 | 0.746667 |
ab2f9c3dd8f46cc3bb9fe742b08054b993bc6c77 | 1,041 | require "language/node"
class Heroku < Formula
desc "Command-line client for the cloud PaaS"
homepage "https://cli.heroku.com"
# heroku should only be updated every 10 releases on multiples of 10
url "https://registry.npmjs.org/heroku/-/heroku-7.0.90.tgz"
sha256 "c64367241578494c1450ce7707d0b3f6d7a72ee3fed3472a8739bb5c61e63e70"
head "https://github.com/heroku/cli.git"
bottle do
cellar :any_skip_relocation
sha256 "8da3ed3c54f3405249924fb078a8278a2988f8b9c190724d72e2518ff346798a" => :high_sierra
sha256 "58f27cfb032853c123c15af2a3a3d5e84d7ec880159cee73141b56206c658d1b" => :sierra
sha256 "ea99b33aab7a011d1e98ce4863ce803132f477288d34f2e8d55122f5cd889a11" => :el_capitan
end
depends_on "node"
def install
inreplace "bin/run", "#!/usr/bin/env node",
"#!#{Formula["node"].opt_bin}/node"
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
system bin/"heroku", "version"
end
end
| 33.580645 | 93 | 0.735831 |
4a12af6abcb3e99f97df79280cf5eaa6c10d3ad0 | 627 |
class Condition < ActiveRecord::Base
acts_as_paranoid
belongs_to :user
validates :name, presence: true
validates :user_id, presence: true
include BelongsToUniverse
include IsContentPage
include Serendipitous::Concern
include Authority::Abilities
self.authorizer_name = 'ExtendedContentAuthorizer'
def self.color
'text-darken-1 lime'
end
def self.text_color
'text-darken-1 lime-text'
end
def self.hex_color
'#CDDC39'
end
def self.icon
'bubble_chart'
end
def self.content_name
'condition'
end
def description
overview_field_value('Description')
end
end
| 15.675 | 52 | 0.725678 |
e26fe04942757e76c79fd5b67ce52fc9633fc096 | 1,642 | cask "imazing" do
version "2.14.6,15535"
sha256 "390e7f8ba1f65218f0f53a4aff8f1c36da5687d3ed85508270dfba66e5ad348e"
url "https://downloads.imazing.com/mac/iMazing/#{version.csv.first}.#{version.csv.second}/iMazing_#{version.csv.first}.#{version.csv.second}.dmg"
name "iMazing"
desc "iPhone management application"
homepage "https://imazing.com/"
livecheck do
url "https://downloads.imazing.com/com.DigiDNA.iMazing#{version.major}Mac.xml"
strategy :sparkle
end
auto_updates true
app "iMazing.app"
uninstall login_item: "iMazing Mini",
quit: [
"com.DigiDNA.iMazing#{version.csv.first}.#{version.csv.second}Mac",
"com.DigiDNA.iMazing#{version.csv.first}.#{version.csv.second}Mac.Mini",
]
zap trash: [
"~/Library/Application Support/iMazing",
"~/Library/Application Support/iMazing Mini",
"~/Library/Application Support/MobileSync/Backup/iMazing.Versions",
"~/Library/Caches/com.DigiDNA.iMazing#{version.major}Mac",
"~/Library/Caches/com.DigiDNA.iMazing#{version.major}Mac.Mini",
"~/Library/Caches/com.plausiblelabs.crashreporter.data/com.DigiDNA.iMazing#{version.major}Mac.Mini",
"~/Library/Caches/iMazing",
"~/Library/Preferences/com.DigiDNA.iMazing#{version.major}Mac.plist",
"~/Library/Preferences/com.DigiDNA.iMazing#{version.major}Mac.Mini.plist",
"/Users/Shared/iMazing Mini",
"/Users/Shared/iMazing",
]
caveats <<~EOS
Performing a zap on this cask removes files pertaining to both #{token}
and imazing-mini, so it should not be done if you only want to uninstall one of them.
EOS
end
| 37.318182 | 147 | 0.70341 |
87ca2069247c65f21d77b724582b194217074b15 | 2,054 | # frozen_string_literal: true
class HoundConfig
CONFIG_FILE = ".hound.yml"
LINTERS = {
Linter::CoffeeScript => { default: true },
Linter::Credo => { default: false },
Linter::Eslint => { default: false },
Linter::Flog => { default: false },
Linter::Go => { default: true },
Linter::Haml => { default: true },
Linter::Jshint => { default: true },
Linter::Flake8 => { default: false },
Linter::Reek => { default: false },
Linter::Remark => { default: false },
Linter::Rubocop => { default: true },
Linter::SassLint => { default: false },
Linter::Scss => { default: true },
Linter::SlimLint => { default: false },
Linter::Stylelint => { default: false },
Linter::Swift => { default: true },
Linter::Tslint => { default: false },
}.freeze
attr_initialize [:commit!, :owner!]
attr_reader :commit
attr_private :owner
def content
@_content ||= default_config.deep_merge(merged_config)
end
def linter_enabled?(name)
config = options_for(name)
!!config["enabled"]
end
def fail_on_violations?
!!content["fail_on_violations"]
end
private
def default_config
LINTERS.each.with_object({}) do |(linter_class, config), result|
name = linter_class.name.demodulize.underscore
result[name] = { "enabled" => config[:default] }
end
end
def merged_config
owner_config.deep_merge(resolved_conflicts_config)
end
def resolved_conflicts_config
ResolveConfigConflicts.call(resolved_aliases_config)
end
def resolved_aliases_config
ResolveConfigAliases.call(normalized_config)
end
def normalized_config
NormalizeConfig.call(parsed_config)
end
def parsed_config
parse(commit.file_content(CONFIG_FILE))
end
def parse(file_content)
Config::Parser.yaml(file_content) || {}
rescue Config::ParserError
raise Config::ParserError, "#{CONFIG_FILE} format is invalid"
end
def options_for(name)
content.fetch(name, {})
end
def owner_config
owner.hound_config_content
end
end
| 24.164706 | 68 | 0.669912 |
21626bc2e95a93f1799702cce8a0b96c4749285c | 530 | # frozen_string_literal: true
workers Integer(ENV['WEB_CONCURRENCY'] || 1)
threads_count = Integer(ENV['MAX_THREADS'] || 5)
threads threads_count, threads_count
preload_app!
rackup DefaultRackup
port 3000
environment ENV['RACK_ENV'] || 'development'
stdout_redirect('/dev/stdout', '/dev/stderr', true)
on_worker_boot do
# Worker specific setup for Rails 4.1+
# See: https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#on-worker-boot
ActiveRecord::Base.establish_connection
end
| 24.090909 | 115 | 0.773585 |
629ed1d64e82775426bc8cd7113cb167d876f84b | 786 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
module Google
module Cloud
module DataCatalog
module V1
VERSION = "0.1.0"
end
end
end
end
| 27.103448 | 74 | 0.732824 |
1c30f9dbd974b6e6f9b264721d4ce72d36c1b348 | 2,288 | require 'ebay/types/xml_requester_credentials'
require 'ebay/types/bot_block_request'
module Ebay # :nodoc:
module Requests # :nodoc:
# == Attributes
# value_array_node :detail_levels, 'DetailLevel', :default_value => []
# text_node :error_language, 'ErrorLanguage', :optional => true
# text_node :message_id, 'MessageID', :optional => true
# text_node :version, 'Version', :optional => true
# text_node :end_user_ip, 'EndUserIP', :optional => true
# object_node :requester_credentials, 'RequesterCredentials', :class => XMLRequesterCredentials, :optional => true
# text_node :error_handling, 'ErrorHandling', :optional => true
# text_node :invocation_id, 'InvocationID', :optional => true
# text_node :warning_level, 'WarningLevel', :optional => true
# object_node :bot_block, 'BotBlock', :class => BotBlockRequest, :optional => true
class Abstract < Base
include XML::Mapping
include Initializer
root_element_name 'AbstractRequest'
value_array_node :detail_levels, 'DetailLevel', :default_value => []
text_node :error_language, 'ErrorLanguage', :optional => true
text_node :message_id, 'MessageID', :optional => true
text_node :version, 'Version', :optional => true
text_node :end_user_ip, 'EndUserIP', :optional => true
object_node :requester_credentials, 'RequesterCredentials', :class => XMLRequesterCredentials, :optional => true
text_node :error_handling, 'ErrorHandling', :optional => true
text_node :invocation_id, 'InvocationID', :optional => true
text_node :warning_level, 'WarningLevel', :optional => true
object_node :bot_block, 'BotBlock', :class => BotBlockRequest, :optional => true
# eBay specifies the detail level as a collection. The usual case is to use
# only a single detail level, so it is more appropriate to add an accessor for
# the normal case.
# Reads the first detail level from the detail_levels Array.
def detail_level
@detail_levels.first
end
# Overwrites the details_levels Array with a new Array containing only the
# value passed in as an argument
def detail_level=(value)
@detail_levels = Array(value)
end
end
end
end
| 46.693878 | 119 | 0.690559 |
217c7d121d8d9873368a9ecf71b4cbf90d7e3c2e | 4,074 | class Libelf < Formula
desc "ELF object file access library"
homepage "https://web.archive.org/web/20181111033959/www.mr511.de/software/english.html"
url "https://www.mirrorservice.org/sites/ftp.netbsd.org/pub/pkgsrc/distfiles/libelf-0.8.13.tar.gz"
mirror "https://fossies.org/linux/misc/old/libelf-0.8.13.tar.gz"
sha256 "591a9b4ec81c1f2042a97aa60564e0cb79d041c52faa7416acb38bc95bd2c76d"
license "LGPL-2.0-or-later"
revision 1
# The formula uses archive.org for the homepage and a mirrored version of the
# last available archive. There seems to be some newer development in the
# ELF Tool Chain project (https://sourceforge.net/p/elftoolchain/wiki/Home/)
# but they don't create separate libelf releases. Altogether, there's nothing
# we can currently check for a new version, so we're skipping this until
# something changes.
livecheck do
skip "No version information available to check"
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "bd7a08bb9750a466bfc18473a61df2095b6d106ffb72f4ed4af706c7385b4202"
sha256 cellar: :any_skip_relocation, big_sur: "8b69f55ccec2aa1bfa85bef3fe071077fe281e2bc63dc33cc4344a1cc02e1e26"
sha256 cellar: :any_skip_relocation, catalina: "b7635245b64cc7d857c92191c40877cba96871d07f4749f620bc96c63cd2635e"
sha256 cellar: :any_skip_relocation, mojave: "7cb626407ee7d61546f2493da91ecc63996d6180949b96b84793e075bd130f2d"
sha256 cellar: :any_skip_relocation, high_sierra: "e11504a15c64cd7fca3248ca7ed14eead25a5d63d8bbd9a8e00f076c56602295"
sha256 cellar: :any_skip_relocation, sierra: "a771e35555810a4910304e3ca5967ea3e4f8cbe45576e5b2dc6b80cd9c1f0f13"
sha256 cellar: :any_skip_relocation, el_capitan: "a06b058c7e401942f442f573b63aa2cdd548b45d38b02b7af92393c67093f56e"
sha256 cellar: :any_skip_relocation, yosemite: "3b4ea9ab20228d9e912f80a330b6d6d093f9bb65a712208c83cd49bdcc4fc9ea"
sha256 cellar: :any_skip_relocation, x86_64_linux: "c72de6e960f70dd98ea52b419d6e254362813c899d4859c4778d385a7c80e0dd"
end
deprecate! date: "2019-05-17", because: :unmaintained # and upstream site is gone
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
on_linux do
keg_only "it conflicts with elfutils, which installs a maintained libelf.a"
end
def install
# Workaround for ancient config files not recognising aarch64 macos.
am = Formula["automake"]
am_share = am.opt_share/"automake-#{am.version.major_minor}"
%w[config.guess config.sub].each do |fn|
cp am_share/fn, fn
end
system "autoreconf", "-fvi"
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}",
"--disable-compat"
# Use separate steps; there is a race in the Makefile.
system "make"
system "make", "install"
end
test do
elf_content = "7F454C460101010000000000000000000200030001000000548004083" \
"4000000000000000000000034002000010000000000000001000000000000000080040" \
"80080040874000000740000000500000000100000B00431DB43B96980040831D2B20CC" \
"D8031C040CD8048656C6C6F20776F726C640A"
File.open(testpath/"elf", "w+b") do |file|
file.write([elf_content].pack("H*"))
end
(testpath/"test.c").write <<~EOS
#include <gelf.h>
#include <fcntl.h>
#include <stdio.h>
int main(void) {
GElf_Ehdr ehdr;
int fd = open("elf", O_RDONLY, 0);
if (elf_version(EV_CURRENT) == EV_NONE) return 1;
Elf *e = elf_begin(fd, ELF_C_READ, NULL);
if (elf_kind(e) != ELF_K_ELF) return 1;
if (gelf_getehdr(e, &ehdr) == NULL) return 1;
printf("%d-bit ELF\\n", gelf_getclass(e) == ELFCLASS32 ? 32 : 64);
return 0;
}
EOS
system ENV.cc, "test.c", "-L#{lib}", "-I#{include}/libelf",
"-lelf", "-o", "test"
assert_match "32-bit ELF", shell_output("./test")
end
end
| 44.769231 | 122 | 0.706186 |
1d2e2fd82f2e791e2a65cb58dd34804ff77177d4 | 429 | require 'test_helper'
class ErrorsControllerTest < ActionDispatch::IntegrationTest
test 'should get bad_request' do
get errors_bad_request_url
assert_response :bad_request
end
test 'should get not_found' do
get errors_not_found_url
assert_response :not_found
end
test 'should get internal_server_error' do
get errors_internal_server_error_url
assert_response :internal_server_error
end
end
| 22.578947 | 60 | 0.79021 |
5d2708750c37c908179889dfba698e1e6f169659 | 1,844 | module JekyllAdmin
class Directory
extend Forwardable
def_delegator :@path, :basename, :name
def_delegator :@path, :mtime, :modified_time
attr_reader :path, :splat, :content_type, :base
include Enumerable
include JekyllAdmin::URLable
include JekyllAdmin::APIable
TYPE = :directory
# Arguments:
#
# path - full path of the directory which its entries will be listed
#
# base - passes site.source to generate `relative_path` needed for `to_api`
#
# content_type - type of the requested directory entries, this is used to generate
# API endpoint of the directory along with `splat`
#
# splat - the requested directory path relative to content namespace
def initialize(path, base: nil, content_type: nil, splat: nil)
@base = Pathname.new base
@content_type = content_type
@splat = Pathname.new splat
@path = Pathname.new path
end
def to_liquid
{
:name => name,
:modified_time => modified_time,
:path => relative_path,
:type => TYPE,
}
end
def relative_path
path.relative_path_from(base).to_s
end
def resource_path
if content_type == "pages"
"/pages/#{splat}/#{name}"
elsif content_type == "data"
"/data/#{splat}/#{name}/"
else
"/collections/#{content_type}/entries/#{splat}/#{name}"
end
end
alias_method :url, :resource_path
def http_url
nil
end
def directories
path.entries.map do |entry|
next if [".", ".."].include? entry.to_s
next unless path.join(entry).directory?
self.class.new(
path.join(entry),
:base => base, :content_type => content_type, :splat => splat
)
end.compact!
end
end
end
| 25.971831 | 86 | 0.605748 |
ab869b400fb37ca2cd4d9ca6eff934b8c52ce2cc | 516 |
#
# Removes simple_form's css class logic.
module SimpleForm
module ActionViewExtensions
module FormHelper
def simple_form_for(record, options = {}, &block)
options[:builder] ||= SimpleForm::FormBuilder
options[:html] ||= {}
unless options[:html].key?(:novalidate)
options[:html][:novalidate] = !SimpleForm.browser_validations
end
with_simple_form_field_error_proc do
form_for(record, options, &block)
end
end
end
end
end
| 24.571429 | 71 | 0.641473 |
3875e1c8feee2df0760c31b40bff4415a124ac0c | 11,936 | require "rubygems"
require "hbc/cask_dependencies"
require "hbc/staged"
require "hbc/verify"
module Hbc
class Installer
# TODO: it is unwise for Hbc::Staged to be a module, when we are
# dealing with both staged and unstaged Casks here. This should
# either be a class which is only sometimes instantiated, or there
# should be explicit checks on whether staged state is valid in
# every method.
include Staged
include Verify
attr_reader :force, :skip_cask_deps
PERSISTENT_METADATA_SUBDIRS = ["gpg"].freeze
def initialize(cask, command: SystemCommand, force: false, skip_cask_deps: false, require_sha: false)
@cask = cask
@command = command
@force = force
@skip_cask_deps = skip_cask_deps
@require_sha = require_sha
end
def self.print_caveats(cask)
odebug "Printing caveats"
return if cask.caveats.empty?
output = capture_output do
cask.caveats.each do |caveat|
if caveat.respond_to?(:eval_and_print)
caveat.eval_and_print(cask)
else
puts caveat
end
end
end
return if output.empty?
ohai "Caveats"
puts output
end
def self.capture_output(&block)
old_stdout = $stdout
$stdout = Buffer.new($stdout.tty?)
block.call
output = $stdout.string
$stdout = old_stdout
output
end
def fetch
odebug "Hbc::Installer#fetch"
satisfy_dependencies
verify_has_sha if @require_sha && !@force
download
verify
end
def stage
odebug "Hbc::Installer#stage"
extract_primary_container
save_caskfile
rescue StandardError => e
purge_versioned_files
raise e
end
def install
odebug "Hbc::Installer#install"
if @cask.installed? && !force
raise CaskAlreadyInstalledAutoUpdatesError, @cask if @cask.auto_updates
raise CaskAlreadyInstalledError, @cask
end
print_caveats
fetch
stage
install_artifacts
enable_accessibility_access
puts summary
end
def summary
s = ""
s << "#{Emoji.install_badge} " if Emoji.enabled?
s << "#{@cask} was successfully installed!"
end
def download
odebug "Downloading"
@downloaded_path = Download.new(@cask, force: false).perform
odebug "Downloaded to -> #{@downloaded_path}"
@downloaded_path
end
def verify_has_sha
odebug "Checking cask has checksum"
return unless @cask.sha256 == :no_check
raise CaskNoShasumError, @cask
end
def verify
Verify.all(@cask, @downloaded_path)
end
def extract_primary_container
odebug "Extracting primary container"
FileUtils.mkdir_p @cask.staged_path
container = if @cask.container && @cask.container.type
Container.from_type(@cask.container.type)
else
Container.for_path(@downloaded_path, @command)
end
unless container
raise CaskError, "Uh oh, could not figure out how to unpack '#{@downloaded_path}'"
end
odebug "Using container class #{container} for #{@downloaded_path}"
container.new(@cask, @downloaded_path, @command).extract
end
def install_artifacts
already_installed_artifacts = []
options = { command: @command, force: force }
odebug "Installing artifacts"
artifacts = Artifact.for_cask(@cask)
odebug "#{artifacts.length} artifact/s defined", artifacts
artifacts.each do |artifact|
odebug "Installing artifact of class #{artifact}"
already_installed_artifacts.unshift(artifact)
artifact.new(@cask, options).install_phase
end
rescue StandardError => e
begin
already_installed_artifacts.each do |artifact|
odebug "Reverting installation of artifact of class #{artifact}"
artifact.new(@cask, options).uninstall_phase
end
ensure
purge_versioned_files
raise e
end
end
# TODO: move dependencies to a separate class
# dependencies should also apply for "brew cask stage"
# override dependencies with --force or perhaps --force-deps
def satisfy_dependencies
return unless @cask.depends_on
ohai "Satisfying dependencies"
macos_dependencies
arch_dependencies
x11_dependencies
formula_dependencies
cask_dependencies unless skip_cask_deps
puts "complete"
end
def macos_dependencies
return unless @cask.depends_on.macos
if @cask.depends_on.macos.first.is_a?(Array)
operator, release = @cask.depends_on.macos.first
unless MacOS.version.send(operator, release)
raise CaskError, "Cask #{@cask} depends on macOS release #{operator} #{release}, but you are running release #{MacOS.version}."
end
elsif @cask.depends_on.macos.length > 1
unless @cask.depends_on.macos.include?(Gem::Version.new(MacOS.version.to_s))
raise CaskError, "Cask #{@cask} depends on macOS release being one of [#{@cask.depends_on.macos.map(&:to_s).join(", ")}], but you are running release #{MacOS.version}."
end
else
unless MacOS.version == @cask.depends_on.macos.first
raise CaskError, "Cask #{@cask} depends on macOS release #{@cask.depends_on.macos.first}, but you are running release #{MacOS.version}."
end
end
end
def arch_dependencies
return if @cask.depends_on.arch.nil?
@current_arch ||= { type: Hardware::CPU.type, bits: Hardware::CPU.bits }
return if @cask.depends_on.arch.any? do |arch|
arch[:type] == @current_arch[:type] &&
Array(arch[:bits]).include?(@current_arch[:bits])
end
raise CaskError, "Cask #{@cask} depends on hardware architecture being one of [#{@cask.depends_on.arch.map(&:to_s).join(", ")}], but you are running #{@current_arch}"
end
def x11_dependencies
return unless @cask.depends_on.x11
raise CaskX11DependencyError, @cask.token unless MacOS::X11.installed?
end
def formula_dependencies
return unless @cask.depends_on.formula && [email protected]_on.formula.empty?
ohai "Installing Formula dependencies from Homebrew"
@cask.depends_on.formula.each do |dep_name|
print "#{dep_name} ... "
installed = @command.run(HOMEBREW_BREW_FILE,
args: ["list", "--versions", dep_name],
print_stderr: false).stdout.include?(dep_name)
if installed
puts "already installed"
else
@command.run!(HOMEBREW_BREW_FILE,
args: ["install", dep_name])
puts "done"
end
end
end
def cask_dependencies
return unless @cask.depends_on.cask && [email protected]_on.cask.empty?
ohai "Installing Cask dependencies: #{@cask.depends_on.cask.join(", ")}"
deps = CaskDependencies.new(@cask)
deps.sorted.each do |dep_token|
puts "#{dep_token} ..."
dep = Hbc.load(dep_token)
if dep.installed?
puts "already installed"
else
Installer.new(dep, force: false, skip_cask_deps: true).install
puts "done"
end
end
end
def print_caveats
self.class.print_caveats(@cask)
end
# TODO: logically could be in a separate class
def enable_accessibility_access
return unless @cask.accessibility_access
ohai "Enabling accessibility access"
if MacOS.version <= :mountain_lion
@command.run!("/usr/bin/touch",
args: [Hbc.pre_mavericks_accessibility_dotfile],
sudo: true)
elsif MacOS.version <= :yosemite
@command.run!("/usr/bin/sqlite3",
args: [
Hbc.tcc_db,
"INSERT OR REPLACE INTO access VALUES('kTCCServiceAccessibility','#{bundle_identifier}',0,1,1,NULL);",
],
sudo: true)
elsif MacOS.version <= :el_capitan
@command.run!("/usr/bin/sqlite3",
args: [
Hbc.tcc_db,
"INSERT OR REPLACE INTO access VALUES('kTCCServiceAccessibility','#{bundle_identifier}',0,1,1,NULL,NULL);",
],
sudo: true)
else
opoo <<-EOS.undent
Accessibility access cannot be enabled automatically on this version of macOS.
See System Preferences to enable it manually.
EOS
end
rescue StandardError => e
purge_versioned_files
raise e
end
def disable_accessibility_access
return unless @cask.accessibility_access
if MacOS.version >= :mavericks && MacOS.version <= :el_capitan
ohai "Disabling accessibility access"
@command.run!("/usr/bin/sqlite3",
args: [
Hbc.tcc_db,
"DELETE FROM access WHERE client='#{bundle_identifier}';",
],
sudo: true)
else
opoo <<-EOS.undent
Accessibility access cannot be disabled automatically on this version of macOS.
See System Preferences to disable it manually.
EOS
end
end
def save_caskfile
timestamp = :now
create = true
savedir = @cask.metadata_subdir("Casks", timestamp, create)
if Dir.entries(savedir).size > 2
# should not happen
raise CaskAlreadyInstalledError, @cask unless force
savedir.rmtree
FileUtils.mkdir_p savedir
end
FileUtils.copy(@cask.sourcefile_path, savedir) if @cask.sourcefile_path
end
def uninstall
odebug "Hbc::Installer#uninstall"
disable_accessibility_access
uninstall_artifacts
purge_versioned_files
purge_caskroom_path if force
end
def uninstall_artifacts
odebug "Un-installing artifacts"
artifacts = Artifact.for_cask(@cask)
odebug "#{artifacts.length} artifact/s defined", artifacts
artifacts.each do |artifact|
odebug "Un-installing artifact of class #{artifact}"
options = { command: @command, force: force }
artifact.new(@cask, options).uninstall_phase
end
end
def zap
ohai %Q(Implied "brew cask uninstall #{@cask}")
uninstall_artifacts
if Artifact::Zap.me?(@cask)
ohai "Dispatching zap stanza"
Artifact::Zap.new(@cask, command: @command).zap_phase
else
opoo "No zap stanza present for Cask '#{@cask}'"
end
ohai "Removing all staged versions of Cask '#{@cask}'"
purge_caskroom_path
end
def gain_permissions_remove(path)
Utils.gain_permissions_remove(path, command: @command)
end
def purge_versioned_files
odebug "Purging files for version #{@cask.version} of Cask #{@cask}"
# versioned staged distribution
gain_permissions_remove(@cask.staged_path) if [email protected]_path.nil? && @cask.staged_path.exist?
# Homebrew-Cask metadata
if @cask.metadata_versioned_container_path.respond_to?(:children) &&
@cask.metadata_versioned_container_path.exist?
@cask.metadata_versioned_container_path.children.each do |subdir|
unless PERSISTENT_METADATA_SUBDIRS.include?(subdir.basename)
gain_permissions_remove(subdir)
end
end
end
@cask.metadata_versioned_container_path.rmdir_if_possible
@cask.metadata_master_container_path.rmdir_if_possible
# toplevel staged distribution
@cask.caskroom_path.rmdir_if_possible
end
def purge_caskroom_path
odebug "Purging all staged versions of Cask #{@cask}"
gain_permissions_remove(@cask.caskroom_path)
end
end
end
| 32 | 178 | 0.631451 |
6abaa614569967f11511d04710522caeb15a3ab5 | 279 | class AddTrashedAndCurrentPriceToVendorProducts < ActiveRecord::Migration
def change
add_column :vendor_products, :trashed, :bool, default: false
add_column :vendor_products, :current_price, :bool, default: true
add_index :vendor_products, :current_price
end
end
| 34.875 | 73 | 0.78853 |
33bfcbe72d7b603f3039f646646adac759faf376 | 5,002 | RSpec.describe Remont::Schema do
it 'processes each matching record' do # rubocop:disable RSpec/ExampleLength
bob = User.create(email: '[email protected]', role: 'admin', processed_at: nil)
schema = described_class.new(model: User, process_timestamp_attribute: :processed_at) do
attribute(:email) { 'email' }
end
now = Time.now.getlocal
Timecop.freeze(now) do
schema.process!
end
bob.reload
expect(bob.email).to eq('email')
expect(bob.processed_at).to be_within(1).of(now)
end
context 'when default process status attribute is overriden' do
let!(:bob) { User.create(email: '[email protected]', role: 'admin', processed_at: nil) }
it 'uses new process status attribute from schema arguments' do
schema = described_class.new(model: User, process_timestamp_attribute: :processed_at) do
attribute(:email) { 'email' }
end
now = Time.now.getlocal
Timecop.freeze(now) do
schema.process!
end
expect(bob.reload.processed_at).to be_within(1).of(now)
end
it 'uses new process status attribute from schema definition' do
schema = described_class.new(model: User) do
with_process_timestamp_attribute :processed_at
attribute(:email) { 'email' }
end
now = Time.now.getlocal
Timecop.freeze(now) do
schema.process!
end
expect(bob.reload.processed_at).to be_within(1).of(now)
end
end
context 'without scope applied' do
let(:schema) do
described_class.new(model: User, process_timestamp_attribute: :processed_at) do
attribute(:email) { 'email' }
end
end
it 'processes all records' do
bob = User.create(email: '[email protected]', role: 'customer', processed_at: nil)
alice = User.create(email: '[email protected]', role: 'admin', processed_at: nil)
schema.process!
expect(bob.reload.processed_at).not_to be_nil
expect(alice.reload.processed_at).not_to be_nil
end
end
context 'with the scope specified' do
let(:schema) do
described_class.new(
model: User,
scope: proc { |relation| relation.where(role: 'customer') },
process_timestamp_attribute: :processed_at
) do
attribute(:email) { 'email' }
end
end
it 'processes only matching records' do
bob = User.create(email: '[email protected]', role: 'customer', processed_at: nil)
alice = User.create(email: '[email protected]', role: 'admin', processed_at: nil)
schema.process!
expect(bob.reload.processed_at).not_to be_nil
expect(alice.reload.processed_at).to be_nil
end
end
context 'when skip process scope is enabled' do
let(:schema) do
described_class.new(model: User, process_timestamp_attribute: :processed_at) do
without_processed
attribute(:email) { 'email' }
end
end
it 'processes only non-processed records' do
last_processing_at = Time.now.getlocal - 60
bob = User.create(email: '[email protected]', role: 'admin', processed_at: last_processing_at)
alice = User.create(email: '[email protected]', role: 'admin', processed_at: nil)
schema.process!
bob.reload
expect(bob.reload.processed_at).to be_within(1).of(last_processing_at)
expect(alice.reload.processed_at).not_to be_nil
end
it "fails if process status attribute isn't configured" do
expect do
described_class.new(model: User, process_timestamp_attribute: nil) do
without_processed
end
end.to raise_error(Remont::Schema::MISSING_PROCESSING_STATUS_ATTR)
end
end
context 'with before callback specified' do
let(:callback) { instance_double('Proc', call: nil) }
let(:schema) do
cb = callback
described_class.new(model: User, process_timestamp_attribute: :processed_at) do
without_processed
attribute(:email) { 'email' }
before { |*args| cb.call(*args) }
end
end
it 'invokes callback for each matching record' do
bob = User.create(email: '[email protected]')
alice = User.create(email: '[email protected]')
schema.process!
expect(callback).to have_received(:call).with(bob)
expect(callback).to have_received(:call).with(alice)
end
end
context 'with after callback specified' do
let(:callback) { instance_double('Proc', call: nil) }
let(:schema) do
cb = callback
described_class.new(model: User, process_timestamp_attribute: :processed_at) do
without_processed
attribute(:email) { 'email' }
after { |*args| cb.call(*args) }
end
end
it 'invokes callback for each matching record' do
bob = User.create(email: '[email protected]')
alice = User.create(email: '[email protected]')
schema.process!
expect(callback).to have_received(:call).with(bob)
expect(callback).to have_received(:call).with(alice)
end
end
end
| 30.13253 | 98 | 0.662935 |
03beb502bb945a6f17ebe2ecdc7b49d667f1c3c7 | 489 | module Travis::API::V3
module Renderer::Error
AVAILABLE_ATTRIBUTES = [ :error_type, :error_message, :resource_type, :permission ]
extend self
def available_attributes
AVAILABLE_ATTRIBUTES
end
def render(error, **options)
{
:@type => 'error'.freeze,
:error_type => error.type,
:error_message => error.message,
**Renderer.render_value(error.payload, script_name: options[:script_name])
}
end
end
end
| 24.45 | 87 | 0.629857 |
d5e86d7354020110628820d486432f68ab958fca | 130,739 | # frozen_string_literal: true
require_relative 'test_helper'
context 'Blocks' do
default_logger = Asciidoctor::LoggerManager.logger
setup do
Asciidoctor::LoggerManager.logger = (@logger = Asciidoctor::MemoryLogger.new)
end
teardown do
Asciidoctor::LoggerManager.logger = default_logger
end
context 'Layout Breaks' do
test 'horizontal rule' do
%w(''' '''' '''''').each do |line|
output = convert_string_to_embedded line
assert_includes output, '<hr>'
end
end
test 'horizontal rule with markdown syntax disabled' do
old_markdown_syntax = Asciidoctor::Compliance.markdown_syntax
begin
Asciidoctor::Compliance.markdown_syntax = false
%w(''' '''' '''''').each do |line|
output = convert_string_to_embedded line
assert_includes output, '<hr>'
end
%w(--- *** ___).each do |line|
output = convert_string_to_embedded line
refute_includes output, '<hr>'
end
ensure
Asciidoctor::Compliance.markdown_syntax = old_markdown_syntax
end
end
test '< 3 chars does not make horizontal rule' do
%w(' '').each do |line|
output = convert_string_to_embedded line
refute_includes output, '<hr>'
assert_includes output, %(<p>#{line}</p>)
end
end
test 'mixed chars does not make horizontal rule' do
[%q(''<), %q('''<), %q(' ' ')].each do |line|
output = convert_string_to_embedded line
refute_includes output, '<hr>'
assert_includes output, %(<p>#{line.sub '<', '<'}</p>)
end
end
test 'horizontal rule between blocks' do
output = convert_string_to_embedded %(Block above\n\n'''\n\nBlock below)
assert_xpath '/hr', output, 1
assert_xpath '/hr/preceding-sibling::*', output, 1
assert_xpath '/hr/following-sibling::*', output, 1
end
test 'page break' do
output = convert_string_to_embedded %(page 1\n\n<<<\n\npage 2)
assert_xpath '/*[@class="page-break"]', output, 1
assert_xpath '/*[@class="page-break"]/preceding-sibling::div/p[text()="page 1"]', output, 1
assert_xpath '/*[@class="page-break"]/following-sibling::div/p[text()="page 2"]', output, 1
end
end
context 'Comments' do
test 'line comment between paragraphs offset by blank lines' do
input = <<~'EOS'
first paragraph
// line comment
second paragraph
EOS
output = convert_string_to_embedded input
refute_match(/line comment/, output)
assert_xpath '//p', output, 2
end
test 'adjacent line comment between paragraphs' do
input = <<~'EOS'
first line
// line comment
second line
EOS
output = convert_string_to_embedded input
refute_match(/line comment/, output)
assert_xpath '//p', output, 1
assert_xpath %(//p[1][text()='first line\nsecond line']), output, 1
end
test 'comment block between paragraphs offset by blank lines' do
input = <<~'EOS'
first paragraph
////
block comment
////
second paragraph
EOS
output = convert_string_to_embedded input
refute_match(/block comment/, output)
assert_xpath '//p', output, 2
end
test 'comment block between paragraphs offset by blank lines inside delimited block' do
input = <<~'EOS'
====
first paragraph
////
block comment
////
second paragraph
====
EOS
output = convert_string_to_embedded input
refute_match(/block comment/, output)
assert_xpath '//p', output, 2
end
test 'adjacent comment block between paragraphs' do
input = <<~'EOS'
first paragraph
////
block comment
////
second paragraph
EOS
output = convert_string_to_embedded input
refute_match(/block comment/, output)
assert_xpath '//p', output, 2
end
test 'can convert with block comment at end of document with trailing newlines' do
input = <<~'EOS'
paragraph
////
block comment
////
EOS
output = convert_string_to_embedded input
refute_match(/block comment/, output)
end
test 'trailing newlines after block comment at end of document does not create paragraph' do
input = <<~'EOS'
paragraph
////
block comment
////
EOS
d = document_from_string input
assert_equal 1, d.blocks.size
assert_xpath '//p', d.convert, 1
end
test 'line starting with three slashes should not be line comment' do
input = '/// not a line comment'
output = convert_string_to_embedded input
refute_empty output.strip, "Line should be emitted => #{input.rstrip}"
end
test 'preprocessor directives should not be processed within comment block within block metadata' do
input = <<~'EOS'
.sample title
////
ifdef::asciidoctor[////]
////
line should be shown
EOS
output = convert_string_to_embedded input
assert_xpath '//p[text()="line should be shown"]', output, 1
end
test 'preprocessor directives should not be processed within comment block' do
input = <<~'EOS'
dummy line
////
ifdef::asciidoctor[////]
////
line should be shown
EOS
output = convert_string_to_embedded input
assert_xpath '//p[text()="line should be shown"]', output, 1
end
test 'should warn if unterminated comment block is detected in body' do
input = <<~'EOS'
before comment block
////
content that has been disabled
supposed to be after comment block, except it got swallowed by block comment
EOS
convert_string_to_embedded input
assert_message @logger, :WARN, '<stdin>: line 3: unterminated comment block', Hash
end
test 'should warn if unterminated comment block is detected inside another block' do
input = <<~'EOS'
before sidebar block
****
////
content that has been disabled
****
supposed to be after sidebar block, except it got swallowed by block comment
EOS
convert_string_to_embedded input
assert_message @logger, :WARN, '<stdin>: line 4: unterminated comment block', Hash
end
# WARNING if first line of content is a directive, it will get interpretted before we know it's a comment block
# it happens because we always look a line ahead...not sure what we can do about it
test 'preprocessor directives should not be processed within comment open block' do
input = <<~'EOS'
[comment]
--
first line of comment
ifdef::asciidoctor[--]
line should not be shown
--
EOS
output = convert_string_to_embedded input
assert_xpath '//p', output, 0
end
# WARNING this assertion fails if the directive is the first line of the paragraph instead of the second
# it happens because we always look a line ahead; not sure what we can do about it
test 'preprocessor directives should not be processed on subsequent lines of a comment paragraph' do
input = <<~'EOS'
[comment]
first line of content
ifdef::asciidoctor[////]
this line should be shown
EOS
output = convert_string_to_embedded input
assert_xpath '//p[text()="this line should be shown"]', output, 1
end
test 'comment style on open block should only skip block' do
input = <<~'EOS'
[comment]
--
skip
this block
--
not this text
EOS
result = convert_string_to_embedded input
assert_xpath '//p', result, 1
assert_xpath '//p[text()="not this text"]', result, 1
end
test 'comment style on paragraph should only skip paragraph' do
input = <<~'EOS'
[comment]
skip
this paragraph
not this text
EOS
result = convert_string_to_embedded input
assert_xpath '//p', result, 1
assert_xpath '//p[text()="not this text"]', result, 1
end
test 'comment style on paragraph should not cause adjacent block to be skipped' do
input = <<~'EOS'
[comment]
skip
this paragraph
[example]
not this text
EOS
result = convert_string_to_embedded input
assert_xpath '/*[@class="exampleblock"]', result, 1
assert_xpath '/*[@class="exampleblock"]//*[normalize-space(text())="not this text"]', result, 1
end
# NOTE this test verifies the nil return value of Parser#next_block
test 'should not drop content that follows skipped content inside a delimited block' do
input = <<~'EOS'
====
paragraph
[comment#idname]
skip
paragraph
====
EOS
result = convert_string_to_embedded input
assert_xpath '/*[@class="exampleblock"]', result, 1
assert_xpath '/*[@class="exampleblock"]//*[@class="paragraph"]', result, 2
assert_xpath '//*[@class="paragraph"][@id="idname"]', result, 0
end
end
context 'Sidebar Blocks' do
test 'should parse sidebar block' do
input = <<~'EOS'
== Section
.Sidebar
****
Content goes here
****
EOS
result = convert_string input
assert_xpath '//*[@class="sidebarblock"]//p', result, 1
end
end
context 'Quote and Verse Blocks' do
test 'quote block with no attribution' do
input = <<~'EOS'
____
A famous quote.
____
EOS
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock > blockquote', output, 1
assert_css '.quoteblock > blockquote > .paragraph > p', output, 1
assert_css '.quoteblock > .attribution', output, 0
assert_xpath '//*[@class="quoteblock"]//p[text()="A famous quote."]', output, 1
end
test 'quote block with attribution' do
input = <<~'EOS'
[quote, Famous Person, Famous Book (1999)]
____
A famous quote.
____
EOS
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock > blockquote', output, 1
assert_css '.quoteblock > blockquote > .paragraph > p', output, 1
assert_css '.quoteblock > .attribution', output, 1
assert_css '.quoteblock > .attribution > cite', output, 1
assert_css '.quoteblock > .attribution > br + cite', output, 1
assert_xpath '//*[@class="quoteblock"]/*[@class="attribution"]/cite[text()="Famous Book (1999)"]', output, 1
attribution = xmlnodes_at_xpath '//*[@class="quoteblock"]/*[@class="attribution"]', output, 1
author = attribution.children.first
assert_equal "#{decode_char 8212} Famous Person", author.text.strip
end
test 'quote block with attribute and id and role shorthand' do
input = <<~'EOS'
[quote#justice-to-all.solidarity, Martin Luther King, Jr.]
____
Injustice anywhere is a threat to justice everywhere.
____
EOS
output = convert_string_to_embedded input
assert_css '.quoteblock', output, 1
assert_css '#justice-to-all.quoteblock.solidarity', output, 1
assert_css '.quoteblock > .attribution', output, 1
end
test 'setting ID using style shorthand should not reset block style' do
input = <<~'EOS'
[quote]
[#justice-to-all.solidarity, Martin Luther King, Jr.]
____
Injustice anywhere is a threat to justice everywhere.
____
EOS
output = convert_string_to_embedded input
assert_css '.quoteblock', output, 1
assert_css '#justice-to-all.quoteblock.solidarity', output, 1
assert_css '.quoteblock > .attribution', output, 1
end
test 'quote block with complex content' do
input = <<~'EOS'
____
A famous quote.
NOTE: _That_ was inspiring.
____
EOS
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock > blockquote', output, 1
assert_css '.quoteblock > blockquote > .paragraph', output, 1
assert_css '.quoteblock > blockquote > .paragraph + .admonitionblock', output, 1
end
test 'quote block with attribution converted to DocBook' do
input = <<~'EOS'
[quote, Famous Person, Famous Book (1999)]
____
A famous quote.
____
EOS
output = convert_string input, backend: :docbook
assert_css 'blockquote', output, 1
assert_css 'blockquote > simpara', output, 1
assert_css 'blockquote > attribution', output, 1
assert_css 'blockquote > attribution > citetitle', output, 1
assert_xpath '//blockquote/attribution/citetitle[text()="Famous Book (1999)"]', output, 1
attribution = xmlnodes_at_xpath '//blockquote/attribution', output, 1
author = attribution.children.first
assert_equal 'Famous Person', author.text.strip
end
test 'epigraph quote block with attribution converted to DocBook' do
input = <<~'EOS'
[.epigraph, Famous Person, Famous Book (1999)]
____
A famous quote.
____
EOS
output = convert_string input, backend: :docbook
assert_css 'epigraph', output, 1
assert_css 'epigraph > simpara', output, 1
assert_css 'epigraph > attribution', output, 1
assert_css 'epigraph > attribution > citetitle', output, 1
assert_xpath '//epigraph/attribution/citetitle[text()="Famous Book (1999)"]', output, 1
attribution = xmlnodes_at_xpath '//epigraph/attribution', output, 1
author = attribution.children.first
assert_equal 'Famous Person', author.text.strip
end
test 'markdown-style quote block with single paragraph and no attribution' do
input = <<~'EOS'
> A famous quote.
> Some more inspiring words.
EOS
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock > blockquote', output, 1
assert_css '.quoteblock > blockquote > .paragraph > p', output, 1
assert_css '.quoteblock > .attribution', output, 0
assert_xpath %(//*[@class="quoteblock"]//p[text()="A famous quote.\nSome more inspiring words."]), output, 1
end
test 'lazy markdown-style quote block with single paragraph and no attribution' do
input = <<~'EOS'
> A famous quote.
Some more inspiring words.
EOS
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock > blockquote', output, 1
assert_css '.quoteblock > blockquote > .paragraph > p', output, 1
assert_css '.quoteblock > .attribution', output, 0
assert_xpath %(//*[@class="quoteblock"]//p[text()="A famous quote.\nSome more inspiring words."]), output, 1
end
test 'markdown-style quote block with multiple paragraphs and no attribution' do
input = <<~'EOS'
> A famous quote.
>
> Some more inspiring words.
EOS
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock > blockquote', output, 1
assert_css '.quoteblock > blockquote > .paragraph > p', output, 2
assert_css '.quoteblock > .attribution', output, 0
assert_xpath %((//*[@class="quoteblock"]//p)[1][text()="A famous quote."]), output, 1
assert_xpath %((//*[@class="quoteblock"]//p)[2][text()="Some more inspiring words."]), output, 1
end
test 'markdown-style quote block with multiple blocks and no attribution' do
input = <<~'EOS'
> A famous quote.
>
> NOTE: Some more inspiring words.
EOS
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock > blockquote', output, 1
assert_css '.quoteblock > blockquote > .paragraph > p', output, 1
assert_css '.quoteblock > blockquote > .admonitionblock', output, 1
assert_css '.quoteblock > .attribution', output, 0
assert_xpath %((//*[@class="quoteblock"]//p)[1][text()="A famous quote."]), output, 1
assert_xpath %((//*[@class="quoteblock"]//*[@class="admonitionblock note"]//*[@class="content"])[1][normalize-space(text())="Some more inspiring words."]), output, 1
end
test 'markdown-style quote block with single paragraph and attribution' do
input = <<~'EOS'
> A famous quote.
> Some more inspiring words.
> -- Famous Person, Famous Source, Volume 1 (1999)
EOS
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock > blockquote', output, 1
assert_css '.quoteblock > blockquote > .paragraph > p', output, 1
assert_xpath %(//*[@class="quoteblock"]//p[text()="A famous quote.\nSome more inspiring words."]), output, 1
assert_css '.quoteblock > .attribution', output, 1
assert_css '.quoteblock > .attribution > cite', output, 1
assert_css '.quoteblock > .attribution > br + cite', output, 1
assert_xpath '//*[@class="quoteblock"]/*[@class="attribution"]/cite[text()="Famous Source, Volume 1 (1999)"]', output, 1
attribution = xmlnodes_at_xpath '//*[@class="quoteblock"]/*[@class="attribution"]', output, 1
author = attribution.children.first
assert_equal "#{decode_char 8212} Famous Person", author.text.strip
end
test 'markdown-style quote block with only attribution' do
input = '> -- Anonymous'
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock > blockquote', output, 1
assert_css '.quoteblock > blockquote > *', output, 0
assert_css '.quoteblock > .attribution', output, 1
assert_xpath %(//*[@class="quoteblock"]//*[@class="attribution"][contains(text(),"Anonymous")]), output, 1
end
test 'should parse credit line in markdown-style quote block like positional block attributes' do
input = <<~'EOS'
> I hold it that a little rebellion now and then is a good thing,
> and as necessary in the political world as storms in the physical.
-- Thomas Jefferson, https://jeffersonpapers.princeton.edu/selected-documents/james-madison-1[The Papers of Thomas Jefferson, Volume 11]
EOS
output = convert_string_to_embedded input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock cite a[href="https://jeffersonpapers.princeton.edu/selected-documents/james-madison-1"]', output, 1
end
test 'quoted paragraph-style quote block with attribution' do
input = <<~'EOS'
"A famous quote.
Some more inspiring words."
-- Famous Person, Famous Source, Volume 1 (1999)
EOS
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock > blockquote', output, 1
assert_xpath %(//*[@class="quoteblock"]/blockquote[normalize-space(text())="A famous quote. Some more inspiring words."]), output, 1
assert_css '.quoteblock > .attribution', output, 1
assert_css '.quoteblock > .attribution > cite', output, 1
assert_css '.quoteblock > .attribution > br + cite', output, 1
assert_xpath '//*[@class="quoteblock"]/*[@class="attribution"]/cite[text()="Famous Source, Volume 1 (1999)"]', output, 1
attribution = xmlnodes_at_xpath '//*[@class="quoteblock"]/*[@class="attribution"]', output, 1
author = attribution.children.first
assert_equal "#{decode_char 8212} Famous Person", author.text.strip
end
test 'should parse credit line in quoted paragraph-style quote block like positional block attributes' do
input = <<~'EOS'
"I hold it that a little rebellion now and then is a good thing,
and as necessary in the political world as storms in the physical."
-- Thomas Jefferson, https://jeffersonpapers.princeton.edu/selected-documents/james-madison-1[The Papers of Thomas Jefferson, Volume 11]
EOS
output = convert_string_to_embedded input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock cite a[href="https://jeffersonpapers.princeton.edu/selected-documents/james-madison-1"]', output, 1
end
test 'single-line verse block without attribution' do
input = <<~'EOS'
[verse]
____
A famous verse.
____
EOS
output = convert_string input
assert_css '.verseblock', output, 1
assert_css '.verseblock > pre', output, 1
assert_css '.verseblock > .attribution', output, 0
assert_css '.verseblock p', output, 0
assert_xpath '//*[@class="verseblock"]/pre[normalize-space(text())="A famous verse."]', output, 1
end
test 'single-line verse block with attribution' do
input = <<~'EOS'
[verse, Famous Poet, Famous Poem]
____
A famous verse.
____
EOS
output = convert_string input
assert_css '.verseblock', output, 1
assert_css '.verseblock p', output, 0
assert_css '.verseblock > pre', output, 1
assert_css '.verseblock > .attribution', output, 1
assert_css '.verseblock > .attribution > cite', output, 1
assert_css '.verseblock > .attribution > br + cite', output, 1
assert_xpath '//*[@class="verseblock"]/*[@class="attribution"]/cite[text()="Famous Poem"]', output, 1
attribution = xmlnodes_at_xpath '//*[@class="verseblock"]/*[@class="attribution"]', output, 1
author = attribution.children.first
assert_equal "#{decode_char 8212} Famous Poet", author.text.strip
end
test 'single-line verse block with attribution converted to DocBook' do
input = <<~'EOS'
[verse, Famous Poet, Famous Poem]
____
A famous verse.
____
EOS
output = convert_string input, backend: :docbook
assert_css 'blockquote', output, 1
assert_css 'blockquote simpara', output, 0
assert_css 'blockquote > literallayout', output, 1
assert_css 'blockquote > attribution', output, 1
assert_css 'blockquote > attribution > citetitle', output, 1
assert_xpath '//blockquote/attribution/citetitle[text()="Famous Poem"]', output, 1
attribution = xmlnodes_at_xpath '//blockquote/attribution', output, 1
author = attribution.children.first
assert_equal 'Famous Poet', author.text.strip
end
test 'single-line epigraph verse block with attribution converted to DocBook' do
input = <<~'EOS'
[verse.epigraph, Famous Poet, Famous Poem]
____
A famous verse.
____
EOS
output = convert_string input, backend: :docbook
assert_css 'epigraph', output, 1
assert_css 'epigraph simpara', output, 0
assert_css 'epigraph > literallayout', output, 1
assert_css 'epigraph > attribution', output, 1
assert_css 'epigraph > attribution > citetitle', output, 1
assert_xpath '//epigraph/attribution/citetitle[text()="Famous Poem"]', output, 1
attribution = xmlnodes_at_xpath '//epigraph/attribution', output, 1
author = attribution.children.first
assert_equal 'Famous Poet', author.text.strip
end
test 'multi-stanza verse block' do
input = <<~'EOS'
[verse]
____
A famous verse.
Stanza two.
____
EOS
output = convert_string input
assert_xpath '//*[@class="verseblock"]', output, 1
assert_xpath '//*[@class="verseblock"]/pre', output, 1
assert_xpath '//*[@class="verseblock"]//p', output, 0
assert_xpath '//*[@class="verseblock"]/pre[contains(text(), "A famous verse.")]', output, 1
assert_xpath '//*[@class="verseblock"]/pre[contains(text(), "Stanza two.")]', output, 1
end
test 'verse block does not contain block elements' do
input = <<~'EOS'
[verse]
____
A famous verse.
....
not a literal
....
____
EOS
output = convert_string input
assert_css '.verseblock', output, 1
assert_css '.verseblock > pre', output, 1
assert_css '.verseblock p', output, 0
assert_css '.verseblock .literalblock', output, 0
end
test 'verse should have normal subs' do
input = <<~'EOS'
[verse]
____
A famous verse
____
EOS
verse = block_from_string input
assert_equal Asciidoctor::Substitutors::NORMAL_SUBS, verse.subs
end
test 'should not recognize callouts in a verse' do
input = <<~'EOS'
[verse]
____
La la la <1>
____
<1> Not pointing to a callout
EOS
output = convert_string_to_embedded input
assert_xpath '//pre[text()="La la la <1>"]', output, 1
assert_message @logger, :WARN, '<stdin>: line 5: no callout found for <1>', Hash
end
test 'should perform normal subs on a verse block' do
input = <<~'EOS'
[verse]
____
_GET /groups/link:#group-id[\{group-id\}]_
____
EOS
output = convert_string_to_embedded input
assert_includes output, '<pre class="content"><em>GET /groups/<a href="#group-id">{group-id}</a></em></pre>'
end
end
context 'Example Blocks' do
test 'can convert example block' do
input = <<~'EOS'
====
This is an example of an example block.
How crazy is that?
====
EOS
output = convert_string input
assert_xpath '//*[@class="exampleblock"]//p', output, 2
end
test 'assigns sequential numbered caption to example block with title' do
input = <<~'EOS'
.Writing Docs with AsciiDoc
====
Here's how you write AsciiDoc.
You just write.
====
.Writing Docs with DocBook
====
Here's how you write DocBook.
You futz with XML.
====
EOS
doc = document_from_string input
assert_equal 1, doc.blocks[0].numeral
assert_equal 1, doc.blocks[0].number
assert_equal 2, doc.blocks[1].numeral
assert_equal 2, doc.blocks[1].number
output = doc.convert
assert_xpath '(//*[@class="exampleblock"])[1]/*[@class="title"][text()="Example 1. Writing Docs with AsciiDoc"]', output, 1
assert_xpath '(//*[@class="exampleblock"])[2]/*[@class="title"][text()="Example 2. Writing Docs with DocBook"]', output, 1
assert_equal 2, doc.attributes['example-number']
end
test 'assigns sequential character caption to example block with title' do
input = <<~'EOS'
:example-number: @
.Writing Docs with AsciiDoc
====
Here's how you write AsciiDoc.
You just write.
====
.Writing Docs with DocBook
====
Here's how you write DocBook.
You futz with XML.
====
EOS
doc = document_from_string input
assert_equal 'A', doc.blocks[0].numeral
assert_equal 'A', doc.blocks[0].number
assert_equal 'B', doc.blocks[1].numeral
assert_equal 'B', doc.blocks[1].number
output = doc.convert
assert_xpath '(//*[@class="exampleblock"])[1]/*[@class="title"][text()="Example A. Writing Docs with AsciiDoc"]', output, 1
assert_xpath '(//*[@class="exampleblock"])[2]/*[@class="title"][text()="Example B. Writing Docs with DocBook"]', output, 1
assert_equal 'B', doc.attributes['example-number']
end
test 'should increment counter for example even when example-number is locked by the API' do
input = <<~'EOS'
.Writing Docs with AsciiDoc
====
Here's how you write AsciiDoc.
You just write.
====
.Writing Docs with DocBook
====
Here's how you write DocBook.
You futz with XML.
====
EOS
doc = document_from_string input, attributes: { 'example-number' => '`' }
output = doc.convert
assert_xpath '(//*[@class="exampleblock"])[1]/*[@class="title"][text()="Example a. Writing Docs with AsciiDoc"]', output, 1
assert_xpath '(//*[@class="exampleblock"])[2]/*[@class="title"][text()="Example b. Writing Docs with DocBook"]', output, 1
assert_equal 'b', doc.attributes['example-number']
end
test 'should use explicit caption if specified' do
input = <<~'EOS'
[caption="Look! "]
.Writing Docs with AsciiDoc
====
Here's how you write AsciiDoc.
You just write.
====
EOS
doc = document_from_string input
assert_nil doc.blocks[0].numeral
output = doc.convert
assert_xpath '(//*[@class="exampleblock"])[1]/*[@class="title"][text()="Look! Writing Docs with AsciiDoc"]', output, 1
refute doc.attributes.key? 'example-number'
end
test 'automatic caption can be turned off and on and modified' do
input = <<~'EOS'
.first example
====
an example
====
:caption:
.second example
====
another example
====
:caption!:
:example-caption: Exhibit
.third example
====
yet another example
====
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="exampleblock"]', output, 3
assert_xpath '(/*[@class="exampleblock"])[1]/*[@class="title"][starts-with(text(), "Example ")]', output, 1
assert_xpath '(/*[@class="exampleblock"])[2]/*[@class="title"][text()="second example"]', output, 1
assert_xpath '(/*[@class="exampleblock"])[3]/*[@class="title"][starts-with(text(), "Exhibit ")]', output, 1
end
test 'should use explicit caption if specified even if block-specific global caption is disabled' do
input = <<~'EOS'
:!example-caption:
[caption="Look! "]
.Writing Docs with AsciiDoc
====
Here's how you write AsciiDoc.
You just write.
====
EOS
doc = document_from_string input
assert_nil doc.blocks[0].numeral
output = doc.convert
assert_xpath '(//*[@class="exampleblock"])[1]/*[@class="title"][text()="Look! Writing Docs with AsciiDoc"]', output, 1
refute doc.attributes.key? 'example-number'
end
test 'should use global caption if specified even if block-specific global caption is disabled' do
input = <<~'EOS'
:!example-caption:
:caption: Look!{sp}
.Writing Docs with AsciiDoc
====
Here's how you write AsciiDoc.
You just write.
====
EOS
doc = document_from_string input
assert_nil doc.blocks[0].numeral
output = doc.convert
assert_xpath '(//*[@class="exampleblock"])[1]/*[@class="title"][text()="Look! Writing Docs with AsciiDoc"]', output, 1
refute doc.attributes.key? 'example-number'
end
test 'should not process caption attribute on block that does not support a caption' do
input = <<~'EOS'
[caption="Look! "]
.No caption here
--
content
--
EOS
doc = document_from_string input
assert_nil doc.blocks[0].caption
assert_equal 'Look! ', (doc.blocks[0].attr 'caption')
output = doc.convert
assert_xpath '(//*[@class="openblock"])[1]/*[@class="title"][text()="No caption here"]', output, 1
end
test 'should create details/summary set if collapsible option is set' do
input = <<~'EOS'
.Toggle Me
[%collapsible]
====
This content is revealed when the user clicks the words "Toggle Me".
====
EOS
output = convert_string_to_embedded input
assert_css 'details', output, 1
assert_css 'details[open]', output, 0
assert_css 'details > summary.title', output, 1
assert_xpath '//details/summary[text()="Toggle Me"]', output, 1
assert_css 'details > summary.title + .content', output, 1
assert_css 'details > summary.title + .content p', output, 1
end
test 'should open details/summary set if collapsible and open options are set' do
input = <<~'EOS'
.Toggle Me
[%collapsible%open]
====
This content is revealed when the user clicks the words "Toggle Me".
====
EOS
output = convert_string_to_embedded input
assert_css 'details', output, 1
assert_css 'details[open]', output, 1
assert_css 'details > summary.title', output, 1
assert_xpath '//details/summary[text()="Toggle Me"]', output, 1
end
test 'should add default summary element if collapsible option is set and title is not specifed' do
input = <<~'EOS'
[%collapsible]
====
This content is revealed when the user clicks the words "Details".
====
EOS
output = convert_string_to_embedded input
assert_css 'details', output, 1
assert_css 'details > summary.title', output, 1
assert_xpath '//details/summary[text()="Details"]', output, 1
end
test 'should not allow collapsible block to increment example number' do
input = <<~'EOS'
.Before
====
before
====
.Show Me The Goods
[%collapsible]
====
This content is revealed when the user clicks the words "Show Me The Goods".
====
.After
====
after
====
EOS
output = convert_string_to_embedded input
assert_xpath '//*[@class="title"][text()="Example 1. Before"]', output, 1
assert_xpath '//*[@class="title"][text()="Example 2. After"]', output, 1
assert_css 'details', output, 1
assert_css 'details > summary.title', output, 1
assert_xpath '//details/summary[text()="Show Me The Goods"]', output, 1
end
test 'should warn if example block is not terminated' do
input = <<~'EOS'
outside
====
inside
still inside
eof
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="exampleblock"]', output, 1
assert_message @logger, :WARN, '<stdin>: line 3: unterminated example block', Hash
end
end
context 'Admonition Blocks' do
test 'caption block-level attribute should be used as caption' do
input = <<~'EOS'
:tip-caption: Pro Tip
[caption="Pro Tip"]
TIP: Override the caption of an admonition block using an attribute entry
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="admonitionblock tip"]//*[@class="icon"]/*[@class="title"][text()="Pro Tip"]', output, 1
end
test 'can override caption of admonition block using document attribute' do
input = <<~'EOS'
:tip-caption: Pro Tip
TIP: Override the caption of an admonition block using an attribute entry
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="admonitionblock tip"]//*[@class="icon"]/*[@class="title"][text()="Pro Tip"]', output, 1
end
test 'blank caption document attribute should not blank admonition block caption' do
input = <<~'EOS'
:caption:
TIP: Override the caption of an admonition block using an attribute entry
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="admonitionblock tip"]//*[@class="icon"]/*[@class="title"][text()="Tip"]', output, 1
end
end
context 'Preformatted Blocks' do
test 'should separate adjacent paragraphs and listing into blocks' do
input = <<~'EOS'
paragraph 1
----
listing content
----
paragraph 2
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="paragraph"]/p', output, 2
assert_xpath '/*[@class="listingblock"]', output, 1
assert_xpath '(/*[@class="paragraph"]/following-sibling::*)[1][@class="listingblock"]', output, 1
end
test 'should warn if listing block is not terminated' do
input = <<~'EOS'
outside
----
inside
still inside
eof
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="listingblock"]', output, 1
assert_message @logger, :WARN, '<stdin>: line 3: unterminated listing block', Hash
end
test 'should not crash if listing block has no lines' do
input = <<~'EOS'
----
----
EOS
output = convert_string_to_embedded input
assert_css 'pre', output, 1
assert_css 'pre:empty', output, 1
end
test 'should preserve newlines in literal block' do
input = <<~'EOS'
....
line one
line two
line three
....
EOS
[true, false].each do |standalone|
output = convert_string input, standalone: standalone
assert_xpath '//pre', output, 1
assert_xpath '//pre/text()', output, 1
text = xmlnodes_at_xpath('//pre/text()', output, 1).text
lines = text.lines
assert_equal 5, lines.size
expected = "line one\n\nline two\n\nline three".lines
assert_equal expected, lines
blank_lines = output.scan(/\n[ \t]*\n/).size
assert blank_lines >= 2
end
end
test 'should preserve newlines in listing block' do
input = <<~'EOS'
----
line one
line two
line three
----
EOS
[true, false].each do |standalone|
output = convert_string input, standalone: standalone
assert_xpath '//pre', output, 1
assert_xpath '//pre/text()', output, 1
text = xmlnodes_at_xpath('//pre/text()', output, 1).text
lines = text.lines
assert_equal 5, lines.size
expected = "line one\n\nline two\n\nline three".lines
assert_equal expected, lines
blank_lines = output.scan(/\n[ \t]*\n/).size
assert blank_lines >= 2
end
end
test 'should preserve newlines in verse block' do
input = <<~'EOS'
--
[verse]
____
line one
line two
line three
____
--
EOS
[true, false].each do |standalone|
output = convert_string input, standalone: standalone
assert_xpath '//*[@class="verseblock"]/pre', output, 1
assert_xpath '//*[@class="verseblock"]/pre/text()', output, 1
text = xmlnodes_at_xpath('//*[@class="verseblock"]/pre/text()', output, 1).text
lines = text.lines
assert_equal 5, lines.size
expected = "line one\n\nline two\n\nline three".lines
assert_equal expected, lines
blank_lines = output.scan(/\n[ \t]*\n/).size
assert blank_lines >= 2
end
end
test 'should strip leading and trailing blank lines when converting verbatim block' do
# NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260
input = <<~EOS
[subs="attributes"]
....
first line
last line
{empty}
....
EOS
doc = document_from_string input, standalone: false
block = doc.blocks.first
assert_equal ['', '', ' first line', '', 'last line', '', '{empty}', ''], block.lines
result = doc.convert
assert_xpath %(//pre[text()=" first line\n\nlast line"]), result, 1
end
test 'should process block with CRLF line endings' do
input = <<~EOS
----\r
source line 1\r
source line 2\r
----\r
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="listingblock"]//pre', output, 1
assert_xpath %(/*[@class="listingblock"]//pre[text()="source line 1\nsource line 2"]), output, 1
end
test 'should remove block indent if indent attribute is 0' do
# NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260
input = <<~EOS
[indent="0"]
----
def names
@names.split
end
----
EOS
# NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260
expected = <<~EOS.chop
def names
@names.split
end
EOS
output = convert_string_to_embedded input
assert_css 'pre', output, 1
assert_css '.listingblock pre', output, 1
result = xmlnodes_at_xpath('//pre', output, 1).text
assert_equal expected, result
end
test 'should not remove block indent if indent attribute is -1' do
# NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260
input = <<~EOS
[indent="-1"]
----
def names
@names.split
end
----
EOS
expected = (input.lines.slice 2, 5).join.chop
output = convert_string_to_embedded input
assert_css 'pre', output, 1
assert_css '.listingblock pre', output, 1
result = xmlnodes_at_xpath('//pre', output, 1).text
assert_equal expected, result
end
test 'should set block indent to value specified by indent attribute' do
# NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260
input = <<~EOS
[indent="1"]
----
def names
@names.split
end
----
EOS
expected = (input.lines.slice 2, 5).map {|l| l.sub ' ', ' ' }.join.chop
output = convert_string_to_embedded input
assert_css 'pre', output, 1
assert_css '.listingblock pre', output, 1
result = xmlnodes_at_xpath('//pre', output, 1).text
assert_equal expected, result
end
test 'should set block indent to value specified by indent document attribute' do
# NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260
input = <<~EOS
:source-indent: 1
[source,ruby]
----
def names
@names.split
end
----
EOS
expected = (input.lines.slice 4, 5).map {|l| l.sub ' ', ' ' }.join.chop
output = convert_string_to_embedded input
assert_css 'pre', output, 1
assert_css '.listingblock pre', output, 1
result = xmlnodes_at_xpath('//pre', output, 1).text
assert_equal expected, result
end
test 'should expand tabs if tabsize attribute is positive' do
input = <<~EOS
:tabsize: 4
[indent=0]
----
\tdef names
\t\[email protected]
\tend
----
EOS
# NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260
expected = <<~EOS.chop
def names
@names.split
end
EOS
output = convert_string_to_embedded input
assert_css 'pre', output, 1
assert_css '.listingblock pre', output, 1
result = xmlnodes_at_xpath('//pre', output, 1).text
assert_equal expected, result
end
test 'literal block should honor nowrap option' do
input = <<~'EOS'
[options="nowrap"]
----
Do not wrap me if I get too long.
----
EOS
output = convert_string_to_embedded input
assert_css 'pre.nowrap', output, 1
end
test 'literal block should set nowrap class if prewrap document attribute is disabled' do
input = <<~'EOS'
:prewrap!:
----
Do not wrap me if I get too long.
----
EOS
output = convert_string_to_embedded input
assert_css 'pre.nowrap', output, 1
end
test 'should preserve guard in front of callout if icons are not enabled' do
input = <<~'EOS'
----
puts 'Hello, World!' # <1>
puts 'Goodbye, World ;(' # <2>
----
EOS
result = convert_string_to_embedded input
assert_include ' # <b class="conum">(1)</b>', result
assert_include ' # <b class="conum">(2)</b>', result
end
test 'should preserve guard around callout if icons are not enabled' do
input = <<~'EOS'
----
<parent> <!--1-->
<child/> <!--2-->
</parent>
----
EOS
result = convert_string_to_embedded input
assert_include ' <!--<b class="conum">(1)</b>-->', result
assert_include ' <!--<b class="conum">(2)</b>-->', result
end
test 'literal block should honor explicit subs list' do
input = <<~'EOS'
[subs="verbatim,quotes"]
----
Map<String, String> *attributes*; //<1>
----
EOS
block = block_from_string input
assert_equal [:specialcharacters, :callouts, :quotes], block.subs
output = block.convert
assert_includes output, 'Map<String, String> <strong>attributes</strong>;'
assert_xpath '//pre/b[text()="(1)"]', output, 1
end
test 'should be able to disable callouts for literal block' do
input = <<~'EOS'
[subs="specialcharacters"]
----
No callout here <1>
----
EOS
block = block_from_string input
assert_equal [:specialcharacters], block.subs
output = block.convert
assert_xpath '//pre/b[text()="(1)"]', output, 0
end
test 'listing block should honor explicit subs list' do
input = <<~'EOS'
[subs="specialcharacters,quotes"]
----
$ *python functional_tests.py*
Traceback (most recent call last):
File "functional_tests.py", line 4, in <module>
assert 'Django' in browser.title
AssertionError
----
EOS
output = convert_string_to_embedded input
assert_css '.listingblock pre', output, 1
assert_css '.listingblock pre strong', output, 1
assert_css '.listingblock pre em', output, 0
input2 = <<~'EOS'
[subs="specialcharacters,macros"]
----
$ pass:quotes[*python functional_tests.py*]
Traceback (most recent call last):
File "functional_tests.py", line 4, in <module>
assert pass:quotes['Django'] in browser.title
AssertionError
----
EOS
output2 = convert_string_to_embedded input2
# FIXME JRuby is adding extra trailing newlines in the second document,
# for now, rstrip is necessary
assert_equal output.rstrip, output2.rstrip
end
test 'first character of block title may be a period if not followed by space' do
input = <<~'EOS'
..gitignore
----
/.bundle/
/build/
/Gemfile.lock
----
EOS
output = convert_string_to_embedded input
assert_xpath '//*[@class="title"][text()=".gitignore"]', output
end
test 'listing block without title should generate screen element in docbook' do
input = <<~'EOS'
----
listing block
----
EOS
output = convert_string_to_embedded input, backend: 'docbook'
assert_xpath '/screen[text()="listing block"]', output, 1
end
test 'listing block with title should generate screen element inside formalpara element in docbook' do
input = <<~'EOS'
.title
----
listing block
----
EOS
output = convert_string_to_embedded input, backend: 'docbook'
assert_xpath '/formalpara', output, 1
assert_xpath '/formalpara/title[text()="title"]', output, 1
assert_xpath '/formalpara/para/screen[text()="listing block"]', output, 1
end
test 'should not prepend caption to title of listing block with title if listing-caption attribute is not set' do
input = <<~'EOS'
.title
----
listing block content
----
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="listingblock"][1]/*[@class="title"][text()="title"]', output, 1
end
test 'should prepend caption specified by listing-caption attribute and number to title of listing block with title' do
input = <<~'EOS'
:listing-caption: Listing
.title
----
listing block content
----
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="listingblock"][1]/*[@class="title"][text()="Listing 1. title"]', output, 1
end
test 'should prepend caption specified by caption attribute on listing block even if listing-caption attribute is not set' do
input = <<~'EOS'
[caption="Listing {counter:listing-number}. "]
.Behold!
----
listing block content
----
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="listingblock"][1]/*[@class="title"][text()="Listing 1. Behold!"]', output, 1
end
test 'listing block without an explicit style and with a second positional argument should be promoted to a source block' do
input = <<~'EOS'
[,ruby]
----
puts 'Hello, Ruby!'
----
EOS
matches = (document_from_string input).find_by context: :listing, style: 'source'
assert_equal 1, matches.length
assert_equal 'ruby', (matches[0].attr 'language')
end
test 'listing block without an explicit style should be promoted to a source block if source-language is set' do
input = <<~'EOS'
:source-language: ruby
----
puts 'Hello, Ruby!'
----
EOS
matches = (document_from_string input).find_by context: :listing, style: 'source'
assert_equal 1, matches.length
assert_equal 'ruby', (matches[0].attr 'language')
end
test 'listing block with an explicit style and a second positional argument should not be promoted to a source block' do
input = <<~'EOS'
[listing,ruby]
----
puts 'Hello, Ruby!'
----
EOS
matches = (document_from_string input).find_by context: :listing
assert_equal 1, matches.length
assert_equal 'listing', matches[0].style
assert_nil matches[0].attr 'language'
end
test 'listing block with an explicit style should not be promoted to a source block if source-language is set' do
input = <<~'EOS'
:source-language: ruby
[listing]
----
puts 'Hello, Ruby!'
----
EOS
matches = (document_from_string input).find_by context: :listing
assert_equal 1, matches.length
assert_equal 'listing', matches[0].style
assert_nil matches[0].attr 'language'
end
test 'source block with no title or language should generate screen element in docbook' do
input = <<~'EOS'
[source]
----
source block
----
EOS
output = convert_string_to_embedded input, backend: 'docbook'
assert_xpath '/screen[@linenumbering="unnumbered"][text()="source block"]', output, 1
end
test 'source block with title and no language should generate screen element inside formalpara element for docbook' do
input = <<~'EOS'
[source]
.title
----
source block
----
EOS
output = convert_string_to_embedded input, backend: 'docbook'
assert_xpath '/formalpara', output, 1
assert_xpath '/formalpara/title[text()="title"]', output, 1
assert_xpath '/formalpara/para/screen[@linenumbering="unnumbered"][text()="source block"]', output, 1
end
end
context 'Open Blocks' do
test 'can convert open block' do
input = <<~'EOS'
--
This is an open block.
It can span multiple lines.
--
EOS
output = convert_string input
assert_xpath '//*[@class="openblock"]//p', output, 2
end
test 'open block can contain another block' do
input = <<~'EOS'
--
This is an open block.
It can span multiple lines.
____
It can hold great quotes like this one.
____
--
EOS
output = convert_string input
assert_xpath '//*[@class="openblock"]//p', output, 3
assert_xpath '//*[@class="openblock"]//*[@class="quoteblock"]', output, 1
end
test 'should transfer id and reftext on open block to DocBook output' do
input = <<~'EOS'
Check out that <<open>>!
[[open,Open Block]]
--
This is an open block.
TIP: An open block can have other blocks inside of it.
--
Back to our regularly scheduled programming.
EOS
output = convert_string input, backend: :docbook, keep_namespaces: true
assert_css 'article:root > para[xml|id="open"]', output, 1
assert_css 'article:root > para[xreflabel="Open Block"]', output, 1
assert_css 'article:root > simpara', output, 2
assert_css 'article:root > para', output, 1
assert_css 'article:root > para > simpara', output, 1
assert_css 'article:root > para > tip', output, 1
end
test 'should transfer id and reftext on open paragraph to DocBook output' do
input = <<~'EOS'
[open#openpara,reftext="Open Paragraph"]
This is an open paragraph.
EOS
output = convert_string input, backend: :docbook, keep_namespaces: true
assert_css 'article:root > simpara', output, 1
assert_css 'article:root > simpara[xml|id="openpara"]', output, 1
assert_css 'article:root > simpara[xreflabel="Open Paragraph"]', output, 1
end
test 'should transfer title on open block to DocBook output' do
input = <<~'EOS'
.Behold the open
--
This is an open block with a title.
--
EOS
output = convert_string input, backend: :docbook
assert_css 'article > formalpara', output, 1
assert_css 'article > formalpara > *', output, 2
assert_css 'article > formalpara > title', output, 1
assert_xpath '/article/formalpara/title[text()="Behold the open"]', output, 1
assert_css 'article > formalpara > para', output, 1
assert_css 'article > formalpara > para > simpara', output, 1
end
test 'should transfer title on open paragraph to DocBook output' do
input = <<~'EOS'
.Behold the open
This is an open paragraph with a title.
EOS
output = convert_string input, backend: :docbook
assert_css 'article > formalpara', output, 1
assert_css 'article > formalpara > *', output, 2
assert_css 'article > formalpara > title', output, 1
assert_xpath '/article/formalpara/title[text()="Behold the open"]', output, 1
assert_css 'article > formalpara > para', output, 1
assert_css 'article > formalpara > para[text()="This is an open paragraph with a title."]', output, 1
end
test 'should transfer role on open block to DocBook output' do
input = <<~'EOS'
[.container]
--
This is an open block.
It holds stuff.
--
EOS
output = convert_string input, backend: :docbook
assert_css 'article > para[role=container]', output, 1
assert_css 'article > para[role=container] > simpara', output, 1
end
test 'should transfer role on open paragraph to DocBook output' do
input = <<~'EOS'
[.container]
This is an open block.
It holds stuff.
EOS
output = convert_string input, backend: :docbook
assert_css 'article > simpara[role=container]', output, 1
end
end
context 'Passthrough Blocks' do
test 'can parse a passthrough block' do
input = <<~'EOS'
++++
This is a passthrough block.
++++
EOS
block = block_from_string input
refute_nil block
assert_equal 1, block.lines.size
assert_equal 'This is a passthrough block.', block.source
end
test 'does not perform subs on a passthrough block by default' do
input = <<~'EOS'
:type: passthrough
++++
This is a '{type}' block.
http://asciidoc.org
image:tiger.png[]
++++
EOS
expected = %(This is a '{type}' block.\nhttp://asciidoc.org\nimage:tiger.png[])
output = convert_string_to_embedded input
assert_equal expected, output.strip
end
test 'does not perform subs on a passthrough block with pass style by default' do
input = <<~'EOS'
:type: passthrough
[pass]
++++
This is a '{type}' block.
http://asciidoc.org
image:tiger.png[]
++++
EOS
expected = %(This is a '{type}' block.\nhttp://asciidoc.org\nimage:tiger.png[])
output = convert_string_to_embedded input
assert_equal expected, output.strip
end
test 'passthrough block honors explicit subs list' do
input = <<~'EOS'
:type: passthrough
[subs="attributes,quotes,macros"]
++++
This is a _{type}_ block.
http://asciidoc.org
++++
EOS
expected = %(This is a <em>passthrough</em> block.\n<a href="http://asciidoc.org" class="bare">http://asciidoc.org</a>)
output = convert_string_to_embedded input
assert_equal expected, output.strip
end
test 'should strip leading and trailing blank lines when converting raw block' do
# NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260
input = <<~EOS
++++
line above
++++
++++
first line
last line
++++
++++
line below
++++
EOS
doc = document_from_string input, standalone: false
block = doc.blocks[1]
assert_equal ['', '', ' first line', '', 'last line', '', ''], block.lines
result = doc.convert
assert_equal "line above\n first line\n\nlast line\nline below", result, 1
end
end
context 'Math blocks' do
test 'should not crash when converting to HTML if stem block is empty' do
input = <<~'EOS'
[stem]
++++
++++
EOS
output = convert_string_to_embedded input
assert_css '.stemblock', output, 1
end
test 'should add LaTeX math delimiters around latexmath block content' do
input = <<~'EOS'
[latexmath]
++++
\sqrt{3x-1}+(1+x)^2 < y
++++
EOS
output = convert_string_to_embedded input
assert_css '.stemblock', output, 1
nodes = xmlnodes_at_xpath '//*[@class="content"]/child::text()', output
assert_equal '\[\sqrt{3x-1}+(1+x)^2 < y\]', nodes.first.to_s.strip
end
test 'should not add LaTeX math delimiters around latexmath block content if already present' do
input = <<~'EOS'
[latexmath]
++++
\[\sqrt{3x-1}+(1+x)^2 < y\]
++++
EOS
output = convert_string_to_embedded input
assert_css '.stemblock', output, 1
nodes = xmlnodes_at_xpath '//*[@class="content"]/child::text()', output
assert_equal '\[\sqrt{3x-1}+(1+x)^2 < y\]', nodes.first.to_s.strip
end
test 'should display latexmath block in alt of equation in DocBook backend' do
input = <<~'EOS'
[latexmath]
++++
\sqrt{3x-1}+(1+x)^2 < y
++++
EOS
expect = <<~'EOS'
<informalequation>
<alt><![CDATA[\sqrt{3x-1}+(1+x)^2 < y]]></alt>
<mathphrase><![CDATA[\sqrt{3x-1}+(1+x)^2 < y]]></mathphrase>
</informalequation>
EOS
output = convert_string_to_embedded input, backend: :docbook
assert_equal expect.strip, output.strip
end
test 'should set autoNumber option for latexmath to none by default' do
input = <<~'EOS'
:stem: latexmath
[stem]
++++
y = x^2
++++
EOS
output = convert_string input
assert_includes output, 'TeX: { equationNumbers: { autoNumber: "none" } }'
end
test 'should set autoNumber option for latexmath to none if eqnums is set to none' do
input = <<~'EOS'
:stem: latexmath
:eqnums: none
[stem]
++++
y = x^2
++++
EOS
output = convert_string input
assert_includes output, 'TeX: { equationNumbers: { autoNumber: "none" } }'
end
test 'should set autoNumber option for latexmath to AMS if eqnums is set' do
input = <<~'EOS'
:stem: latexmath
:eqnums:
[stem]
++++
\begin{equation}
y = x^2
\end{equation}
++++
EOS
output = convert_string input
assert_includes output, 'TeX: { equationNumbers: { autoNumber: "AMS" } }'
end
test 'should set autoNumber option for latexmath to all if eqnums is set to all' do
input = <<~'EOS'
:stem: latexmath
:eqnums: all
[stem]
++++
y = x^2
++++
EOS
output = convert_string input
assert_includes output, 'TeX: { equationNumbers: { autoNumber: "all" } }'
end
test 'should not split equation in AsciiMath block at single newline' do
input = <<~'EOS'
[asciimath]
++++
f: bbb"N" -> bbb"N"
f: x |-> x + 1
++++
EOS
expected = <<~'EOS'.chop
\$f: bbb"N" -> bbb"N"
f: x |-> x + 1\$
EOS
output = convert_string_to_embedded input
assert_css '.stemblock', output, 1
nodes = xmlnodes_at_xpath '//*[@class="content"]', output
assert_equal expected, nodes.first.inner_html.strip
end
test 'should split equation in AsciiMath block at escaped newline' do
input = <<~'EOS'
[asciimath]
++++
f: bbb"N" -> bbb"N" \
f: x |-> x + 1
++++
EOS
expected = <<~'EOS'.chop
\$f: bbb"N" -> bbb"N"\$
\$f: x |-> x + 1\$
EOS
output = convert_string_to_embedded input
assert_css '.stemblock', output, 1
nodes = xmlnodes_at_xpath '//*[@class="content"]', output
assert_equal expected, nodes.first.inner_html.strip
end
test 'should split equation in AsciiMath block at sequence of escaped newlines' do
input = <<~'EOS'
[asciimath]
++++
f: bbb"N" -> bbb"N" \
\
f: x |-> x + 1
++++
EOS
expected = <<~'EOS'.chop
\$f: bbb"N" -> bbb"N"\$
<br>
\$f: x |-> x + 1\$
EOS
output = convert_string_to_embedded input
assert_css '.stemblock', output, 1
nodes = xmlnodes_at_xpath '//*[@class="content"]', output
assert_equal expected, nodes.first.inner_html.strip
end
test 'should split equation in AsciiMath block at newline sequence and preserve breaks' do
input = <<~'EOS'
[asciimath]
++++
f: bbb"N" -> bbb"N"
f: x |-> x + 1
++++
EOS
expected = <<~'EOS'.chop
\$f: bbb"N" -> bbb"N"\$
<br>
<br>
\$f: x |-> x + 1\$
EOS
output = convert_string_to_embedded input
assert_css '.stemblock', output, 1
nodes = xmlnodes_at_xpath '//*[@class="content"]', output
assert_equal expected, nodes.first.inner_html.strip
end
test 'should add AsciiMath delimiters around asciimath block content' do
input = <<~'EOS'
[asciimath]
++++
sqrt(3x-1)+(1+x)^2 < y
++++
EOS
output = convert_string_to_embedded input
assert_css '.stemblock', output, 1
nodes = xmlnodes_at_xpath '//*[@class="content"]/child::text()', output
assert_equal '\$sqrt(3x-1)+(1+x)^2 < y\$', nodes.first.to_s.strip
end
test 'should not add AsciiMath delimiters around asciimath block content if already present' do
input = <<~'EOS'
[asciimath]
++++
\$sqrt(3x-1)+(1+x)^2 < y\$
++++
EOS
output = convert_string_to_embedded input
assert_css '.stemblock', output, 1
nodes = xmlnodes_at_xpath '//*[@class="content"]/child::text()', output
assert_equal '\$sqrt(3x-1)+(1+x)^2 < y\$', nodes.first.to_s.strip
end
test 'should convert contents of asciimath block to MathML in DocBook output if asciimath gem is available' do
asciimath_available = !(Asciidoctor::Helpers.require_library 'asciimath', true, :ignore).nil?
input = <<~'EOS'
[asciimath]
++++
x+b/(2a)<+-sqrt((b^2)/(4a^2)-c/a)
++++
[asciimath]
++++
++++
EOS
expect = <<~'EOS'.chop
<informalequation>
<mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>x</mml:mi><mml:mo>+</mml:mo><mml:mfrac><mml:mi>b</mml:mi><mml:mrow><mml:mn>2</mml:mn><mml:mi>a</mml:mi></mml:mrow></mml:mfrac><mml:mo><</mml:mo><mml:mo>±</mml:mo><mml:msqrt><mml:mrow><mml:mfrac><mml:msup><mml:mi>b</mml:mi><mml:mn>2</mml:mn></mml:msup><mml:mrow><mml:mn>4</mml:mn><mml:msup><mml:mi>a</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:mfrac><mml:mo>−</mml:mo><mml:mfrac><mml:mi>c</mml:mi><mml:mi>a</mml:mi></mml:mfrac></mml:mrow></mml:msqrt></mml:math>
</informalequation>
<informalequation>
<mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML"></mml:math>
</informalequation>
EOS
using_memory_logger do |logger|
doc = document_from_string input, backend: :docbook, standalone: false
actual = doc.convert
if asciimath_available
assert_equal expect, actual.strip
assert_equal :loaded, doc.converter.instance_variable_get(:@asciimath_status)
else
assert_message logger, :WARN, 'optional gem \'asciimath\' is not available. Functionality disabled.'
assert_equal :unavailable, doc.converter.instance_variable_get(:@asciimath_status)
end
end
end
test 'should output title for latexmath block if defined' do
input = <<~'EOS'
.The Lorenz Equations
[latexmath]
++++
\begin{aligned}
\dot{x} & = \sigma(y-x) \\
\dot{y} & = \rho x - y - xz \\
\dot{z} & = -\beta z + xy
\end{aligned}
++++
EOS
output = convert_string_to_embedded input
assert_css '.stemblock', output, 1
assert_css '.stemblock .title', output, 1
assert_xpath '//*[@class="title"][text()="The Lorenz Equations"]', output, 1
end
test 'should output title for asciimath block if defined' do
input = <<~'EOS'
.Simple fraction
[asciimath]
++++
a//b
++++
EOS
output = convert_string_to_embedded input
assert_css '.stemblock', output, 1
assert_css '.stemblock .title', output, 1
assert_xpath '//*[@class="title"][text()="Simple fraction"]', output, 1
end
test 'should add AsciiMath delimiters around stem block content if stem attribute is asciimath, empty, or not set' do
input = <<~'EOS'
[stem]
++++
sqrt(3x-1)+(1+x)^2 < y
++++
EOS
[
{},
{ 'stem' => '' },
{ 'stem' => 'asciimath' },
{ 'stem' => 'bogus' },
].each do |attributes|
output = convert_string_to_embedded input, attributes: attributes
assert_css '.stemblock', output, 1
nodes = xmlnodes_at_xpath '//*[@class="content"]/child::text()', output
assert_equal '\$sqrt(3x-1)+(1+x)^2 < y\$', nodes.first.to_s.strip
end
end
test 'should add LaTeX math delimiters around stem block content if stem attribute is latexmath, latex, or tex' do
input = <<~'EOS'
[stem]
++++
\sqrt{3x-1}+(1+x)^2 < y
++++
EOS
[
{ 'stem' => 'latexmath' },
{ 'stem' => 'latex' },
{ 'stem' => 'tex' },
].each do |attributes|
output = convert_string_to_embedded input, attributes: attributes
assert_css '.stemblock', output, 1
nodes = xmlnodes_at_xpath '//*[@class="content"]/child::text()', output
assert_equal '\[\sqrt{3x-1}+(1+x)^2 < y\]', nodes.first.to_s.strip
end
end
test 'should allow stem style to be set using second positional argument of block attributes' do
input = <<~'EOS'
:stem: latexmath
[stem,asciimath]
++++
sqrt(3x-1)+(1+x)^2 < y
++++
EOS
doc = document_from_string input
stemblock = doc.blocks[0]
assert_equal :stem, stemblock.context
assert_equal 'asciimath', stemblock.attributes['style']
output = doc.convert standalone: false
assert_css '.stemblock', output, 1
nodes = xmlnodes_at_xpath '//*[@class="content"]/child::text()', output
assert_equal '\$sqrt(3x-1)+(1+x)^2 < y\$', nodes.first.to_s.strip
end
end
context 'Custom Blocks' do
test 'should not warn if block style is unknown' do
input = <<~'EOS'
[foo]
--
bar
--
EOS
convert_string_to_embedded input
assert_empty @logger.messages
end
test 'should log debug message if block style is unknown and debug level is enabled' do
input = <<~'EOS'
[foo]
--
bar
--
EOS
using_memory_logger Logger::Severity::DEBUG do |logger|
convert_string_to_embedded input
assert_message logger, :DEBUG, '<stdin>: line 2: unknown style for open block: foo', Hash
end
end
end
context 'Metadata' do
test 'block title above section gets carried over to first block in section' do
input = <<~'EOS'
.Title
== Section
paragraph
EOS
output = convert_string input
assert_xpath '//*[@class="paragraph"]', output, 1
assert_xpath '//*[@class="paragraph"]/*[@class="title"][text()="Title"]', output, 1
assert_xpath '//*[@class="paragraph"]/p[text()="paragraph"]', output, 1
end
test 'block title above document title demotes document title to a section title' do
input = <<~'EOS'
.Block title
= Section Title
section paragraph
EOS
output = convert_string input
assert_xpath '//*[@id="header"]/*', output, 0
assert_xpath '//*[@id="preamble"]/*', output, 0
assert_xpath '//*[@id="content"]/h1[text()="Section Title"]', output, 1
assert_xpath '//*[@class="paragraph"]', output, 1
assert_xpath '//*[@class="paragraph"]/*[@class="title"][text()="Block title"]', output, 1
assert_message @logger, :ERROR, '<stdin>: line 2: level 0 sections can only be used when doctype is book', Hash
end
test 'block title above document title gets carried over to first block in first section if no preamble' do
input = <<~'EOS'
:doctype: book
.Block title
= Document Title
== First Section
paragraph
EOS
doc = document_from_string input
# NOTE block title demotes document title to level-0 section
refute doc.header?
output = doc.convert
assert_xpath '//*[@class="sect1"]//*[@class="paragraph"]/*[@class="title"][text()="Block title"]', output, 1
end
test 'should apply substitutions to a block title in normal order' do
input = <<~'EOS'
.{link-url}[{link-text}]{tm}
The one and only!
EOS
output = convert_string_to_embedded input, attributes: {
'link-url' => 'https://acme.com',
'link-text' => 'ACME',
'tm' => '(TM)',
}
assert_css '.title', output, 1
assert_css '.title a[href="https://acme.com"]', output, 1
assert_xpath %(//*[@class="title"][contains(text(),"#{decode_char 8482}")]), output, 1
end
test 'empty attribute list should not appear in output' do
input = <<~'EOS'
[]
--
Block content
--
EOS
output = convert_string_to_embedded input
assert_includes output, 'Block content'
refute_includes output, '[]'
end
test 'empty block anchor should not appear in output' do
input = <<~'EOS'
[[]]
--
Block content
--
EOS
output = convert_string_to_embedded input
assert_includes output, 'Block content'
refute_includes output, '[[]]'
end
end
context 'Images' do
test 'can convert block image with alt text defined in macro' do
input = 'image::images/tiger.png[Tiger]'
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"]', output, 1
end
test 'converts SVG image using img element by default' do
input = 'image::tiger.svg[Tiger]'
output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SERVER
assert_xpath '/*[@class="imageblock"]//img[@src="tiger.svg"][@alt="Tiger"]', output, 1
end
test 'converts interactive SVG image with alt text using object element' do
input = <<~'EOS'
:imagesdir: images
[%interactive]
image::tiger.svg[Tiger,100]
EOS
output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SERVER
assert_xpath '/*[@class="imageblock"]//object[@type="image/svg+xml"][@data="images/tiger.svg"][@width="100"]/span[@class="alt"][text()="Tiger"]', output, 1
end
test 'converts SVG image with alt text using img element when safe mode is secure' do
input = <<~'EOS'
[%interactive]
image::images/tiger.svg[Tiger,100]
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//img[@src="images/tiger.svg"][@alt="Tiger"]', output, 1
end
test 'inserts fallback image for SVG inside object element using same dimensions' do
input = <<~'EOS'
:imagesdir: images
[%interactive]
image::tiger.svg[Tiger,100,fallback=tiger.png]
EOS
output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SERVER
assert_xpath '/*[@class="imageblock"]//object[@type="image/svg+xml"][@data="images/tiger.svg"][@width="100"]/img[@src="images/tiger.png"][@width="100"]', output, 1
end
test 'detects SVG image URI that contains a query string' do
input = <<~'EOS'
:imagesdir: images
[%interactive]
image::http://example.org/tiger.svg?foo=bar[Tiger,100]
EOS
output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SERVER
assert_xpath '/*[@class="imageblock"]//object[@type="image/svg+xml"][@data="http://example.org/tiger.svg?foo=bar"][@width="100"]/span[@class="alt"][text()="Tiger"]', output, 1
end
test 'detects SVG image when format attribute is svg' do
input = <<~'EOS'
:imagesdir: images
[%interactive]
image::http://example.org/tiger-svg[Tiger,100,format=svg]
EOS
output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SERVER
assert_xpath '/*[@class="imageblock"]//object[@type="image/svg+xml"][@data="http://example.org/tiger-svg"][@width="100"]/span[@class="alt"][text()="Tiger"]', output, 1
end
test 'converts to inline SVG image when inline option is set on block' do
input = <<~'EOS'
:imagesdir: fixtures
[%inline]
image::circle.svg[Tiger,100]
EOS
output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SERVER, attributes: { 'docdir' => testdir }
assert_match(/<svg\s[^>]*width="100"[^>]*>/, output, 1)
refute_match(/<svg\s[^>]*width="500"[^>]*>/, output)
refute_match(/<svg\s[^>]*height="500"[^>]*>/, output)
refute_match(/<svg\s[^>]*style="[^>]*>/, output)
end
test 'should honor percentage width for SVG image with inline option' do
input = <<~'EOS'
:imagesdir: fixtures
image::circle.svg[Circle,50%,opts=inline]
EOS
output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SERVER, attributes: { 'docdir' => testdir }
assert_match(/<svg\s[^>]*width="50%"[^>]*>/, output, 1)
end
test 'should not crash if explicit width on SVG image block is an integer' do
input = <<~'EOS'
:imagesdir: fixtures
image::circle.svg[Circle,opts=inline]
EOS
doc = document_from_string input, safe: Asciidoctor::SafeMode::SERVER, attributes: { 'docdir' => testdir }
doc.blocks[0].set_attr 'width', 50
output = doc.convert
assert_match %r/<svg\s[^>]*width="50"[^>]*>/, output, 1
end
test 'converts to inline SVG image when inline option is set on block and data-uri is set on document' do
input = <<~'EOS'
:imagesdir: fixtures
:data-uri:
[%inline]
image::circle.svg[Tiger,100]
EOS
output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SERVER, attributes: { 'docdir' => testdir }
assert_match(/<svg\s[^>]*width="100">/, output, 1)
end
test 'should not throw exception if SVG to inline is empty' do
input = 'image::empty.svg[nada,opts=inline]'
output = convert_string_to_embedded input, safe: :safe, attributes: { 'docdir' => testdir, 'imagesdir' => 'fixtures' }
assert_xpath '//svg', output, 0
assert_xpath '//span[@class="alt"][text()="nada"]', output, 1
assert_message @logger, :WARN, '~contents of SVG is empty:'
end
test 'should not throw exception if SVG to inline contains an incomplete start tag and explicit width is specified' do
input = 'image::incomplete.svg[,200,opts=inline]'
output = convert_string_to_embedded input, safe: :safe, attributes: { 'docdir' => testdir, 'imagesdir' => 'fixtures' }
assert_xpath '//svg', output, 1
assert_xpath '//span[@class="alt"]', output, 0
end
test 'embeds remote SVG to inline when inline option is set on block and allow-uri-read is set on document' do
input = %(image::http://#{resolve_localhost}:9876/fixtures/circle.svg[Circle,100,100,opts=inline])
output = using_test_webserver do
convert_string_to_embedded input, safe: :safe, attributes: { 'allow-uri-read' => '' }
end
assert_css 'svg', output, 1
assert_css 'svg[style]', output, 0
assert_css 'svg[width="100"]', output, 1
assert_css 'svg[height="100"]', output, 1
assert_css 'svg circle', output, 1
end
test 'converts to alt text for SVG with inline option set if SVG cannot be read' do
input = <<~'EOS'
[%inline]
image::no-such-image.svg[Alt Text]
EOS
output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SERVER
assert_xpath '//span[@class="alt"][text()="Alt Text"]', output, 1
assert_message @logger, :WARN, '~SVG does not exist or cannot be read'
end
test 'can convert block image with alt text defined in macro containing square bracket' do
input = 'image::images/tiger.png[A [Bengal] Tiger]'
output = convert_string input
img = xmlnodes_at_xpath '//img', output, 1
assert_equal 'A [Bengal] Tiger', img.attr('alt')
end
test 'can convert block image with target containing spaces' do
input = 'image::images/big tiger.png[A Big Tiger]'
output = convert_string input
img = xmlnodes_at_xpath '//img', output, 1
assert_equal 'images/big%20tiger.png', img.attr('src')
assert_equal 'A Big Tiger', img.attr('alt')
end
test 'should not recognize block image if target has leading or trailing spaces' do
[' tiger.png', 'tiger.png '].each do |target|
input = %(image::#{target}[Tiger])
output = convert_string_to_embedded input
assert_xpath '//img', output, 0
end
end
test 'can convert block image with alt text defined in block attribute above macro' do
input = <<~'EOS'
[Tiger]
image::images/tiger.png[]
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"]', output, 1
end
test 'alt text in macro overrides alt text above macro' do
input = <<~'EOS'
[Alt Text]
image::images/tiger.png[Tiger]
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"]', output, 1
end
test 'should substitute attribute references in alt text defined in image block macro' do
input = <<~'EOS'
:alt-text: Tiger
image::images/tiger.png[{alt-text}]
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"]', output, 1
end
test 'should set direction CSS class on image if float attribute is set' do
input = <<~'EOS'
[float=left]
image::images/tiger.png[Tiger]
EOS
output = convert_string_to_embedded input
assert_css '.imageblock.left', output, 1
assert_css '.imageblock[style]', output, 0
end
test 'should set text alignment CSS class on image if align attribute is set' do
input = <<~'EOS'
[align=center]
image::images/tiger.png[Tiger]
EOS
output = convert_string_to_embedded input
assert_css '.imageblock.text-center', output, 1
assert_css '.imageblock[style]', output, 0
end
test 'style attribute is dropped from image macro' do
input = <<~'EOS'
[style=value]
image::images/tiger.png[Tiger]
EOS
doc = document_from_string input
img = doc.blocks[0]
refute img.attributes.key? 'style'
assert_nil img.style
end
test 'should apply specialcharacters and replacement substitutions to alt text' do
input = 'A tiger\'s "roar" is < a bear\'s "growl"'
expected = 'A tiger’s "roar" is < a bear’s "growl"'
result = convert_string_to_embedded %(image::images/tiger-roar.png[#{input}])
assert_includes result, %(alt="#{expected}")
end
test 'should not encode double quotes in alt text when converting to DocBook' do
input = 'Select "File > Open"'
expected = 'Select "File > Open"'
result = convert_string_to_embedded %(image::images/open.png[#{input}]), backend: :docbook
assert_includes result, %(<phrase>#{expected}</phrase>)
end
test 'should auto-generate alt text for block image if alt text is not specified' do
input = 'image::images/lions-and-tigers.png[]'
image = block_from_string input
assert_equal 'lions and tigers', (image.attr 'alt')
assert_equal 'lions and tigers', (image.attr 'default-alt')
output = image.convert
assert_xpath '/*[@class="imageblock"]//img[@src="images/lions-and-tigers.png"][@alt="lions and tigers"]', output, 1
end
test 'can convert block image with alt text and height and width' do
input = 'image::images/tiger.png[Tiger, 200, 300]'
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"][@width="200"][@height="300"]', output, 1
end
test 'should not output empty width attribute if positional width attribute is empty' do
input = 'image::images/tiger.png[Tiger,]'
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//img[@src="images/tiger.png"]', output, 1
assert_xpath '/*[@class="imageblock"]//img[@src="images/tiger.png"][@width]', output, 0
end
test 'can convert block image with link' do
input = <<~'EOS'
image::images/tiger.png[Tiger, link='http://en.wikipedia.org/wiki/Tiger']
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//a[@class="image"][@href="http://en.wikipedia.org/wiki/Tiger"]/img[@src="images/tiger.png"][@alt="Tiger"]', output, 1
end
test 'adds rel=noopener attribute to block image with link that targets _blank window' do
input = 'image::images/tiger.png[Tiger,link=http://en.wikipedia.org/wiki/Tiger,window=_blank]'
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//a[@class="image"][@href="http://en.wikipedia.org/wiki/Tiger"][@target="_blank"][@rel="noopener"]/img[@src="images/tiger.png"][@alt="Tiger"]', output, 1
end
test 'adds rel=noopener attribute to block image with link that targets name window when the noopener option is set' do
input = 'image::images/tiger.png[Tiger,link=http://en.wikipedia.org/wiki/Tiger,window=name,opts=noopener]'
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//a[@class="image"][@href="http://en.wikipedia.org/wiki/Tiger"][@target="name"][@rel="noopener"]/img[@src="images/tiger.png"][@alt="Tiger"]', output, 1
end
test 'adds rel=nofollow attribute to block image with a link when the nofollow option is set' do
input = 'image::images/tiger.png[Tiger,link=http://en.wikipedia.org/wiki/Tiger,opts=nofollow]'
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//a[@class="image"][@href="http://en.wikipedia.org/wiki/Tiger"][@rel="nofollow"]/img[@src="images/tiger.png"][@alt="Tiger"]', output, 1
end
test 'can convert block image with caption' do
input = <<~'EOS'
.The AsciiDoc Tiger
image::images/tiger.png[Tiger]
EOS
doc = document_from_string input
assert_equal 1, doc.blocks[0].numeral
output = doc.convert
assert_xpath '//*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"]', output, 1
assert_xpath '//*[@class="imageblock"]/*[@class="title"][text()="Figure 1. The AsciiDoc Tiger"]', output, 1
assert_equal 1, doc.attributes['figure-number']
end
test 'can convert block image with explicit caption' do
input = <<~'EOS'
[caption="Voila! "]
.The AsciiDoc Tiger
image::images/tiger.png[Tiger]
EOS
doc = document_from_string input
assert_nil doc.blocks[0].numeral
output = doc.convert
assert_xpath '//*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"]', output, 1
assert_xpath '//*[@class="imageblock"]/*[@class="title"][text()="Voila! The AsciiDoc Tiger"]', output, 1
refute doc.attributes.key?('figure-number')
end
test 'can align image in DocBook backend' do
input = 'image::images/sunset.jpg[Sunset,align=right]'
output = convert_string_to_embedded input, backend: :docbook
assert_xpath '//imagedata', output, 1
assert_xpath '//imagedata[@align="right"]', output, 1
end
test 'should set content width and depth in DocBook backend if no scaling' do
input = 'image::images/sunset.jpg[Sunset,500,332]'
output = convert_string_to_embedded input, backend: :docbook
assert_xpath '//imagedata', output, 1
assert_xpath '//imagedata[@contentwidth="500"]', output, 1
assert_xpath '//imagedata[@contentdepth="332"]', output, 1
assert_xpath '//imagedata[@width]', output, 0
assert_xpath '//imagedata[@depth]', output, 0
end
test 'can scale image in DocBook backend' do
input = 'image::images/sunset.jpg[Sunset,500,332,scale=200]'
output = convert_string_to_embedded input, backend: :docbook
assert_xpath '//imagedata', output, 1
assert_xpath '//imagedata[@scale="200"]', output, 1
assert_xpath '//imagedata[@width]', output, 0
assert_xpath '//imagedata[@depth]', output, 0
assert_xpath '//imagedata[@contentwidth]', output, 0
assert_xpath '//imagedata[@contentdepth]', output, 0
end
test 'scale image width in DocBook backend' do
input = 'image::images/sunset.jpg[Sunset,500,332,scaledwidth=25%]'
output = convert_string_to_embedded input, backend: :docbook
assert_xpath '//imagedata', output, 1
assert_xpath '//imagedata[@width="25%"]', output, 1
assert_xpath '//imagedata[@depth]', output, 0
assert_xpath '//imagedata[@contentwidth]', output, 0
assert_xpath '//imagedata[@contentdepth]', output, 0
end
test 'adds % to scaled width if no units given in DocBook backend ' do
input = 'image::images/sunset.jpg[Sunset,scaledwidth=25]'
output = convert_string_to_embedded input, backend: :docbook
assert_xpath '//imagedata', output, 1
assert_xpath '//imagedata[@width="25%"]', output, 1
end
test 'keeps attribute reference unprocessed if image target is missing attribute reference and attribute-missing is skip' do
input = <<~'EOS'
:attribute-missing: skip
image::{bogus}[]
EOS
output = convert_string_to_embedded input
assert_css 'img[src="{bogus}"]', output, 1
assert_empty @logger
end
test 'should not drop line if image target is missing attribute reference and attribute-missing is drop' do
input = <<~'EOS'
:attribute-missing: drop
image::{bogus}/photo.jpg[]
EOS
output = convert_string_to_embedded input
assert_css 'img[src="/photo.jpg"]', output, 1
assert_empty @logger
end
test 'drops line if image target is missing attribute reference and attribute-missing is drop-line' do
input = <<~'EOS'
:attribute-missing: drop-line
image::{bogus}[]
EOS
output = convert_string_to_embedded input
assert_empty output.strip
assert_message @logger, :INFO, 'dropping line containing reference to missing attribute: bogus'
end
test 'should not drop line if image target resolves to blank and attribute-missing is drop-line' do
input = <<~'EOS'
:attribute-missing: drop-line
image::{blank}[]
EOS
output = convert_string_to_embedded input
assert_css 'img[src=""]', output, 1
assert_empty @logger
end
test 'dropped image does not break processing of following section and attribute-missing is drop-line' do
input = <<~'EOS'
:attribute-missing: drop-line
image::{bogus}[]
== Section Title
EOS
output = convert_string_to_embedded input
assert_css 'img', output, 0
assert_css 'h2', output, 1
refute_includes output, '== Section Title'
assert_message @logger, :INFO, 'dropping line containing reference to missing attribute: bogus'
end
test 'should pass through image that references uri' do
input = <<~'EOS'
:imagesdir: images
image::http://asciidoc.org/images/tiger.png[Tiger]
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//img[@src="http://asciidoc.org/images/tiger.png"][@alt="Tiger"]', output, 1
end
test 'should encode spaces in image target if value is a URI' do
input = 'image::http://example.org/svg?digraph=digraph G { a -> b; }[diagram]'
output = convert_string_to_embedded input
assert_xpath %(/*[@class="imageblock"]//img[@src="http://example.org/svg?digraph=digraph%20G%20{%20a%20-#{decode_char 62}%20b;%20}"]), output, 1
end
test 'can resolve image relative to imagesdir' do
input = <<~'EOS'
:imagesdir: images
image::tiger.png[Tiger]
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"]', output, 1
end
test 'embeds base64-encoded data uri for image when data-uri attribute is set' do
input = <<~'EOS'
:data-uri:
:imagesdir: fixtures
image::dot.gif[Dot]
EOS
doc = document_from_string input, safe: Asciidoctor::SafeMode::SAFE, attributes: { 'docdir' => testdir }
assert_equal 'fixtures', doc.attributes['imagesdir']
output = doc.convert
assert_xpath '//img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Dot"]', output, 1
end
test 'embeds SVG image with image/svg+xml mimetype when file extension is .svg' do
input = <<~'EOS'
:imagesdir: fixtures
:data-uri:
image::circle.svg[Tiger,100]
EOS
output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SERVER, attributes: { 'docdir' => testdir }
assert_xpath '//img[starts-with(@src,"data:image/svg+xml;base64,")]', output, 1
end
test 'embeds empty base64-encoded data uri for unreadable image when data-uri attribute is set' do
input = <<~'EOS'
:data-uri:
:imagesdir: fixtures
image::unreadable.gif[Dot]
EOS
doc = document_from_string input, safe: Asciidoctor::SafeMode::SAFE, attributes: { 'docdir' => testdir }
assert_equal 'fixtures', doc.attributes['imagesdir']
output = doc.convert
assert_xpath '//img[@src="data:image/gif;base64,"]', output, 1
assert_message @logger, :WARN, '~image to embed not found or not readable'
end
test 'embeds base64-encoded data uri with application/octet-stream mimetype when file extension is missing' do
input = <<~'EOS'
:data-uri:
:imagesdir: fixtures
image::dot[Dot]
EOS
doc = document_from_string input, safe: Asciidoctor::SafeMode::SAFE, attributes: { 'docdir' => testdir }
assert_equal 'fixtures', doc.attributes['imagesdir']
output = doc.convert
assert_xpath '//img[starts-with(@src,"data:application/octet-stream;base64,")]', output, 1
end
test 'embeds base64-encoded data uri for remote image when data-uri attribute is set' do
input = <<~EOS
:data-uri:
image::http://#{resolve_localhost}:9876/fixtures/dot.gif[Dot]
EOS
output = using_test_webserver do
convert_string_to_embedded input, safe: :safe, attributes: { 'allow-uri-read' => '' }
end
assert_xpath '//img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Dot"]', output, 1
end
test 'embeds base64-encoded data uri for remote image when imagesdir is a URI and data-uri attribute is set' do
input = <<~EOS
:data-uri:
:imagesdir: http://#{resolve_localhost}:9876/fixtures
image::dot.gif[Dot]
EOS
output = using_test_webserver do
convert_string_to_embedded input, safe: :safe, attributes: { 'allow-uri-read' => '' }
end
assert_xpath '//img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Dot"]', output, 1
end
test 'uses remote image uri when data-uri attribute is set and image cannot be retrieved' do
image_uri = "http://#{resolve_localhost}:9876/fixtures/missing-image.gif"
input = <<~EOS
:data-uri:
image::#{image_uri}[Missing image]
EOS
output = using_test_webserver do
convert_string_to_embedded input, safe: :safe, attributes: { 'allow-uri-read' => '' }
end
assert_xpath %(/*[@class="imageblock"]//img[@src="#{image_uri}"][@alt="Missing image"]), output, 1
assert_message @logger, :WARN, '~could not retrieve image data from URI'
end
test 'uses remote image uri when data-uri attribute is set and allow-uri-read is not set' do
image_uri = "http://#{resolve_localhost}:9876/fixtures/dot.gif"
input = <<~EOS
:data-uri:
image::#{image_uri}[Dot]
EOS
output = using_test_webserver do
convert_string_to_embedded input, safe: :safe
end
assert_xpath %(/*[@class="imageblock"]//img[@src="#{image_uri}"][@alt="Dot"]), output, 1
end
test 'can handle embedded data uri images' do
input = 'image::data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=[Dot]'
output = convert_string_to_embedded input
assert_xpath '//img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Dot"]', output, 1
end
test 'can handle embedded data uri images when data-uri attribute is set' do
input = <<~'EOS'
:data-uri:
image::data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=[Dot]
EOS
output = convert_string_to_embedded input
assert_xpath '//img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Dot"]', output, 1
end
test 'cleans reference to ancestor directories in imagesdir before reading image if safe mode level is at least SAFE' do
input = <<~'EOS'
:data-uri:
:imagesdir: ../..//fixtures/./../../fixtures
image::dot.gif[Dot]
EOS
doc = document_from_string input, safe: Asciidoctor::SafeMode::SAFE, attributes: { 'docdir' => testdir }
assert_equal '../..//fixtures/./../../fixtures', doc.attributes['imagesdir']
output = doc.convert
# image target resolves to fixtures/dot.gif relative to docdir (which is explicitly set to the directory of this file)
# the reference cannot fall outside of the document directory in safe mode
assert_xpath '//img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Dot"]', output, 1
assert_message @logger, :WARN, 'image has illegal reference to ancestor of jail; recovering automatically'
end
test 'cleans reference to ancestor directories in target before reading image if safe mode level is at least SAFE' do
input = <<~'EOS'
:data-uri:
:imagesdir: ./
image::../..//fixtures/./../../fixtures/dot.gif[Dot]
EOS
doc = document_from_string input, safe: Asciidoctor::SafeMode::SAFE, attributes: { 'docdir' => testdir }
assert_equal './', doc.attributes['imagesdir']
output = doc.convert
# image target resolves to fixtures/dot.gif relative to docdir (which is explicitly set to the directory of this file)
# the reference cannot fall outside of the document directory in safe mode
assert_xpath '//img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Dot"]', output, 1
assert_message @logger, :WARN, 'image has illegal reference to ancestor of jail; recovering automatically'
end
end
context 'Media' do
test 'should detect and convert video macro' do
input = 'video::cats-vs-dogs.avi[]'
output = convert_string_to_embedded input
assert_css 'video', output, 1
assert_css 'video[src="cats-vs-dogs.avi"]', output, 1
end
test 'should detect and convert video macro with positional attributes for poster and dimensions' do
input = 'video::cats-vs-dogs.avi[cats-and-dogs.png, 200, 300]'
output = convert_string_to_embedded input
assert_css 'video', output, 1
assert_css 'video[src="cats-vs-dogs.avi"]', output, 1
assert_css 'video[poster="cats-and-dogs.png"]', output, 1
assert_css 'video[width="200"]', output, 1
assert_css 'video[height="300"]', output, 1
end
test 'should set direction CSS class on video block if float attribute is set' do
input = 'video::cats-vs-dogs.avi[cats-and-dogs.png,float=right]'
output = convert_string_to_embedded input
assert_css 'video', output, 1
assert_css 'video[src="cats-vs-dogs.avi"]', output, 1
assert_css '.videoblock.right', output, 1
end
test 'should set text alignment CSS class on video block if align attribute is set' do
input = 'video::cats-vs-dogs.avi[cats-and-dogs.png,align=center]'
output = convert_string_to_embedded input
assert_css 'video', output, 1
assert_css 'video[src="cats-vs-dogs.avi"]', output, 1
assert_css '.videoblock.text-center', output, 1
end
test 'video macro should honor all options' do
input = 'video::cats-vs-dogs.avi[options="autoplay,muted,nocontrols,loop",preload="metadata"]'
output = convert_string_to_embedded input
assert_css 'video', output, 1
assert_css 'video[autoplay]', output, 1
assert_css 'video[muted]', output, 1
assert_css 'video:not([controls])', output, 1
assert_css 'video[loop]', output, 1
assert_css 'video[preload=metadata]', output, 1
end
test 'video macro should add time range anchor with start time if start attribute is set' do
input = 'video::cats-vs-dogs.avi[start="30"]'
output = convert_string_to_embedded input
assert_css 'video', output, 1
assert_xpath '//video[@src="cats-vs-dogs.avi#t=30"]', output, 1
end
test 'video macro should add time range anchor with end time if end attribute is set' do
input = 'video::cats-vs-dogs.avi[end="30"]'
output = convert_string_to_embedded input
assert_css 'video', output, 1
assert_xpath '//video[@src="cats-vs-dogs.avi#t=,30"]', output, 1
end
test 'video macro should add time range anchor with start and end time if start and end attributes are set' do
input = 'video::cats-vs-dogs.avi[start="30",end="60"]'
output = convert_string_to_embedded input
assert_css 'video', output, 1
assert_xpath '//video[@src="cats-vs-dogs.avi#t=30,60"]', output, 1
end
test 'video macro should use imagesdir attribute to resolve target and poster' do
input = <<~'EOS'
:imagesdir: assets
video::cats-vs-dogs.avi[cats-and-dogs.png, 200, 300]
EOS
output = convert_string_to_embedded input
assert_css 'video', output, 1
assert_css 'video[src="assets/cats-vs-dogs.avi"]', output, 1
assert_css 'video[poster="assets/cats-and-dogs.png"]', output, 1
assert_css 'video[width="200"]', output, 1
assert_css 'video[height="300"]', output, 1
end
test 'video macro should not use imagesdir attribute to resolve target if target is a URL' do
input = <<~'EOS'
:imagesdir: assets
video::http://example.org/videos/cats-vs-dogs.avi[]
EOS
output = convert_string_to_embedded input
assert_css 'video', output, 1
assert_css 'video[src="http://example.org/videos/cats-vs-dogs.avi"]', output, 1
end
test 'video macro should output custom HTML with iframe for vimeo service' do
input = 'video::67480300[vimeo, 400, 300, start=60, options="autoplay,muted"]'
output = convert_string_to_embedded input
assert_css 'video', output, 0
assert_css 'iframe', output, 1
assert_css 'iframe[src="https://player.vimeo.com/video/67480300?autoplay=1&muted=1#at=60"]', output, 1
assert_css 'iframe[width="400"]', output, 1
assert_css 'iframe[height="300"]', output, 1
end
test 'video macro should allow hash for vimeo video to be specified in video ID' do
input = 'video::67480300/123456789[vimeo, 400, 300, options=loop]'
output = convert_string_to_embedded input
assert_css 'video', output, 0
assert_css 'iframe', output, 1
assert_css 'iframe[src="https://player.vimeo.com/video/67480300?h=123456789&loop=1"]', output, 1
assert_css 'iframe[width="400"]', output, 1
assert_css 'iframe[height="300"]', output, 1
end
test 'video macro should allow hash for vimeo video to be specified using hash attribute' do
input = 'video::67480300[vimeo, 400, 300, options=loop, hash=123456789]'
output = convert_string_to_embedded input
assert_css 'video', output, 0
assert_css 'iframe', output, 1
assert_css 'iframe[src="https://player.vimeo.com/video/67480300?h=123456789&loop=1"]', output, 1
assert_css 'iframe[width="400"]', output, 1
assert_css 'iframe[height="300"]', output, 1
end
test 'video macro should output custom HTML with iframe for youtube service' do
input = 'video::U8GBXvdmHT4/PLg7s6cbtAD15Das5LK9mXt_g59DLWxKUe[youtube, 640, 360, start=60, options="autoplay,muted,modest", theme=light]'
output = convert_string_to_embedded input
assert_css 'video', output, 0
assert_css 'iframe', output, 1
assert_css 'iframe[src="https://www.youtube.com/embed/U8GBXvdmHT4?rel=0&start=60&autoplay=1&mute=1&list=PLg7s6cbtAD15Das5LK9mXt_g59DLWxKUe&modestbranding=1&theme=light"]', output, 1
assert_css 'iframe[width="640"]', output, 1
assert_css 'iframe[height="360"]', output, 1
end
test 'video macro should output custom HTML with iframe for youtube service with dynamic playlist' do
input = 'video::SCZF6I-Rc4I,AsKGOeonbIs,HwrPhOp6-aM[youtube, 640, 360, start=60, options=autoplay]'
output = convert_string_to_embedded input
assert_css 'video', output, 0
assert_css 'iframe', output, 1
assert_css 'iframe[src="https://www.youtube.com/embed/SCZF6I-Rc4I?rel=0&start=60&autoplay=1&playlist=SCZF6I-Rc4I,AsKGOeonbIs,HwrPhOp6-aM"]', output, 1
assert_css 'iframe[width="640"]', output, 1
assert_css 'iframe[height="360"]', output, 1
end
test 'should detect and convert audio macro' do
input = 'audio::podcast.mp3[]'
output = convert_string_to_embedded input
assert_css 'audio', output, 1
assert_css 'audio[src="podcast.mp3"]', output, 1
end
test 'audio macro should use imagesdir attribute to resolve target' do
input = <<~'EOS'
:imagesdir: assets
audio::podcast.mp3[]
EOS
output = convert_string_to_embedded input
assert_css 'audio', output, 1
assert_css 'audio[src="assets/podcast.mp3"]', output, 1
end
test 'audio macro should not use imagesdir attribute to resolve target if target is a URL' do
input = <<~'EOS'
:imagesdir: assets
video::http://example.org/podcast.mp3[]
EOS
output = convert_string_to_embedded input
assert_css 'video', output, 1
assert_css 'video[src="http://example.org/podcast.mp3"]', output, 1
end
test 'audio macro should honor all options' do
input = 'audio::podcast.mp3[options="autoplay,nocontrols,loop"]'
output = convert_string_to_embedded input
assert_css 'audio', output, 1
assert_css 'audio[autoplay]', output, 1
assert_css 'audio:not([controls])', output, 1
assert_css 'audio[loop]', output, 1
end
test 'audio macro should support start and end time' do
input = 'audio::podcast.mp3[start=1,end=2]'
output = convert_string_to_embedded input
assert_css 'audio', output, 1
assert_css 'audio[controls]', output, 1
assert_css 'audio[src="podcast.mp3#t=1,2"]', output, 1
end
end
context 'Admonition icons' do
test 'can resolve icon relative to default iconsdir' do
input = <<~'EOS'
:icons:
[TIP]
You can use icons for admonitions by setting the 'icons' attribute.
EOS
output = convert_string input, safe: Asciidoctor::SafeMode::SERVER
assert_xpath '//*[@class="admonitionblock tip"]//*[@class="icon"]/img[@src="./images/icons/tip.png"][@alt="Tip"]', output, 1
end
test 'can resolve icon relative to custom iconsdir' do
input = <<~'EOS'
:icons:
:iconsdir: icons
[TIP]
You can use icons for admonitions by setting the 'icons' attribute.
EOS
output = convert_string input, safe: Asciidoctor::SafeMode::SERVER
assert_xpath '//*[@class="admonitionblock tip"]//*[@class="icon"]/img[@src="icons/tip.png"][@alt="Tip"]', output, 1
end
test 'should add file extension to custom icon if not specified' do
input = <<~'EOS'
:icons: font
:iconsdir: images/icons
[TIP,icon=a]
Override the icon of an admonition block using an attribute
EOS
output = convert_string input, safe: Asciidoctor::SafeMode::SERVER
assert_xpath '//*[@class="admonitionblock tip"]//*[@class="icon"]/img[@src="images/icons/a.png"]', output, 1
end
test 'should allow icontype to be specified when using built-in admonition icon' do
input = 'TIP: Set the icontype using either the icontype attribute on the icons attribute.'
[
{ 'icons' => '', 'ext' => 'png' },
{ 'icons' => '', 'icontype' => 'jpg', 'ext' => 'jpg' },
{ 'icons' => 'jpg', 'ext' => 'jpg' },
{ 'icons' => 'image', 'ext' => 'png' },
].each do |attributes|
expected_src = %(./images/icons/tip.#{attributes.delete 'ext'})
output = convert_string input, attributes: attributes
assert_xpath %(//*[@class="admonitionblock tip"]//*[@class="icon"]/img[@src="#{expected_src}"]), output, 1
end
end
test 'should allow icontype to be specified when using custom admonition icon' do
input = <<~'EOS'
[TIP,icon=hint]
Set the icontype using either the icontype attribute on the icons attribute.
EOS
[
{ 'icons' => '', 'ext' => 'png' },
{ 'icons' => '', 'icontype' => 'jpg', 'ext' => 'jpg' },
{ 'icons' => 'jpg', 'ext' => 'jpg' },
{ 'icons' => 'image', 'ext' => 'png' },
].each do |attributes|
expected_src = %(./images/icons/hint.#{attributes.delete 'ext'})
output = convert_string input, attributes: attributes
assert_xpath %(//*[@class="admonitionblock tip"]//*[@class="icon"]/img[@src="#{expected_src}"]), output, 1
end
end
test 'embeds base64-encoded data uri of icon when data-uri attribute is set and safe mode level is less than SECURE' do
input = <<~'EOS'
:icons:
:iconsdir: fixtures
:icontype: gif
:data-uri:
[TIP]
You can use icons for admonitions by setting the 'icons' attribute.
EOS
output = convert_string input, safe: Asciidoctor::SafeMode::SAFE, attributes: { 'docdir' => testdir }
assert_xpath '//*[@class="admonitionblock tip"]//*[@class="icon"]/img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Tip"]', output, 1
end
test 'should embed base64-encoded data uri of custom icon when data-uri attribute is set' do
input = <<~'EOS'
:icons:
:iconsdir: fixtures
:icontype: gif
:data-uri:
[TIP,icon=tip]
You can set a custom icon using the icon attribute on the block.
EOS
output = convert_string input, safe: Asciidoctor::SafeMode::SAFE, attributes: { 'docdir' => testdir }
assert_xpath '//*[@class="admonitionblock tip"]//*[@class="icon"]/img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Tip"]', output, 1
end
test 'does not embed base64-encoded data uri of icon when safe mode level is SECURE or greater' do
input = <<~'EOS'
:icons:
:iconsdir: fixtures
:icontype: gif
:data-uri:
[TIP]
You can use icons for admonitions by setting the 'icons' attribute.
EOS
output = convert_string input, attributes: { 'icons' => '' }
assert_xpath '//*[@class="admonitionblock tip"]//*[@class="icon"]/img[@src="fixtures/tip.gif"][@alt="Tip"]', output, 1
end
test 'cleans reference to ancestor directories before reading icon if safe mode level is at least SAFE' do
input = <<~'EOS'
:icons:
:iconsdir: ../fixtures
:icontype: gif
:data-uri:
[TIP]
You can use icons for admonitions by setting the 'icons' attribute.
EOS
output = convert_string input, safe: Asciidoctor::SafeMode::SAFE, attributes: { 'docdir' => testdir }
assert_xpath '//*[@class="admonitionblock tip"]//*[@class="icon"]/img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Tip"]', output, 1
assert_message @logger, :WARN, 'image has illegal reference to ancestor of jail; recovering automatically'
end
test 'should import Font Awesome and use font-based icons when value of icons attribute is font' do
input = <<~'EOS'
:icons: font
[TIP]
You can use icons for admonitions by setting the 'icons' attribute.
EOS
output = convert_string input, safe: Asciidoctor::SafeMode::SERVER
assert_css %(html > head > link[rel="stylesheet"][href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/#{Asciidoctor::FONT_AWESOME_VERSION}/css/font-awesome.min.css"]), output, 1
assert_xpath '//*[@class="admonitionblock tip"]//*[@class="icon"]/i[@class="fa icon-tip"]', output, 1
end
test 'font-based icon should not override icon specified on admonition' do
input = <<~'EOS'
:icons: font
:iconsdir: images/icons
[TIP,icon=a.png]
Override the icon of an admonition block using an attribute
EOS
output = convert_string input, safe: Asciidoctor::SafeMode::SERVER
assert_xpath '//*[@class="admonitionblock tip"]//*[@class="icon"]/i[@class="fa icon-tip"]', output, 0
assert_xpath '//*[@class="admonitionblock tip"]//*[@class="icon"]/img[@src="images/icons/a.png"]', output, 1
end
test 'should use http uri scheme for assets when asset-uri-scheme is http' do
input = <<~'EOS'
:asset-uri-scheme: http
:icons: font
:source-highlighter: highlightjs
TIP: You can control the URI scheme used for assets with the asset-uri-scheme attribute
[source,ruby]
puts "AsciiDoc, FTW!"
EOS
output = convert_string input, safe: Asciidoctor::SafeMode::SAFE
assert_css %(html > head > link[rel="stylesheet"][href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/#{Asciidoctor::FONT_AWESOME_VERSION}/css/font-awesome.min.css"]), output, 1
assert_css %(html > body > script[src="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/#{Asciidoctor::HIGHLIGHT_JS_VERSION}/highlight.min.js"]), output, 1
end
test 'should use no uri scheme for assets when asset-uri-scheme is blank' do
input = <<~'EOS'
:asset-uri-scheme:
:icons: font
:source-highlighter: highlightjs
TIP: You can control the URI scheme used for assets with the asset-uri-scheme attribute
[source,ruby]
puts "AsciiDoc, FTW!"
EOS
output = convert_string input, safe: Asciidoctor::SafeMode::SAFE
assert_css %(html > head > link[rel="stylesheet"][href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/#{Asciidoctor::FONT_AWESOME_VERSION}/css/font-awesome.min.css"]), output, 1
assert_css %(html > body > script[src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/#{Asciidoctor::HIGHLIGHT_JS_VERSION}/highlight.min.js"]), output, 1
end
end
context 'Image paths' do
test 'restricts access to ancestor directories when safe mode level is at least SAFE' do
input = 'image::asciidoctor.png[Asciidoctor]'
basedir = testdir
block = block_from_string input, attributes: { 'docdir' => basedir }
doc = block.document
assert doc.safe >= Asciidoctor::SafeMode::SAFE
assert_equal File.join(basedir, 'images'), block.normalize_asset_path('images')
assert_equal File.join(basedir, 'etc/images'), block.normalize_asset_path("#{disk_root}etc/images")
assert_equal File.join(basedir, 'images'), block.normalize_asset_path('../../images')
end
test 'does not restrict access to ancestor directories when safe mode is disabled' do
input = 'image::asciidoctor.png[Asciidoctor]'
basedir = testdir
block = block_from_string input, safe: Asciidoctor::SafeMode::UNSAFE, attributes: { 'docdir' => basedir }
doc = block.document
assert_equal Asciidoctor::SafeMode::UNSAFE, doc.safe
assert_equal File.join(basedir, 'images'), block.normalize_asset_path('images')
absolute_path = "#{disk_root}etc/images"
assert_equal absolute_path, block.normalize_asset_path(absolute_path)
assert_equal File.expand_path(File.join(basedir, '../../images')), block.normalize_asset_path('../../images')
end
end
context 'Source code' do
test 'should support fenced code block using backticks' do
input = <<~'EOS'
```
puts "Hello, World!"
```
EOS
output = convert_string_to_embedded input
assert_css '.listingblock', output, 1
assert_css '.listingblock pre code', output, 1
assert_css '.listingblock pre code:not([class])', output, 1
end
test 'should not recognize fenced code blocks with more than three delimiters' do
input = <<~'EOS'
````ruby
puts "Hello, World!"
````
~~~~ javascript
alert("Hello, World!")
~~~~
EOS
output = convert_string_to_embedded input
assert_css '.listingblock', output, 0
end
test 'should support fenced code blocks with languages' do
input = <<~'EOS'
```ruby
puts "Hello, World!"
```
``` javascript
alert("Hello, World!")
```
EOS
output = convert_string_to_embedded input
assert_css '.listingblock', output, 2
assert_css '.listingblock pre code.language-ruby[data-lang=ruby]', output, 1
assert_css '.listingblock pre code.language-javascript[data-lang=javascript]', output, 1
end
test 'should support fenced code blocks with languages and numbering' do
input = <<~'EOS'
```ruby,numbered
puts "Hello, World!"
```
``` javascript, numbered
alert("Hello, World!")
```
EOS
output = convert_string_to_embedded input
assert_css '.listingblock', output, 2
assert_css '.listingblock pre code.language-ruby[data-lang=ruby]', output, 1
assert_css '.listingblock pre code.language-javascript[data-lang=javascript]', output, 1
end
end
context 'Abstract and Part Intro' do
test 'should make abstract on open block without title a quote block for article' do
input = <<~'EOS'
= Article
[abstract]
--
This article is about stuff.
And other stuff.
--
== Section One
content
EOS
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock.abstract', output, 1
assert_css '#preamble .quoteblock', output, 1
assert_css '.quoteblock > blockquote', output, 1
assert_css '.quoteblock > blockquote > .paragraph', output, 2
end
test 'should make abstract on open block with title a quote block with title for article' do
input = <<~'EOS'
= Article
.My abstract
[abstract]
--
This article is about stuff.
--
== Section One
content
EOS
output = convert_string input
assert_css '.quoteblock', output, 1
assert_css '.quoteblock.abstract', output, 1
assert_css '#preamble .quoteblock', output, 1
assert_css '.quoteblock > .title', output, 1
assert_css '.quoteblock > .title + blockquote', output, 1
assert_css '.quoteblock > .title + blockquote > .paragraph', output, 1
end
test 'should allow abstract in document with title if doctype is book' do
input = <<~'EOS'
= Book
:doctype: book
[abstract]
Abstract for book with title is valid
EOS
output = convert_string input
assert_css '.abstract', output, 1
end
test 'should not allow abstract as direct child of document if doctype is book' do
input = <<~'EOS'
:doctype: book
[abstract]
Abstract for book without title is invalid.
EOS
output = convert_string input
assert_css '.abstract', output, 0
assert_message @logger, :WARN, 'abstract block cannot be used in a document without a title when doctype is book. Excluding block content.'
end
test 'should make abstract on open block without title converted to DocBook' do
input = <<~'EOS'
= Article
[abstract]
--
This article is about stuff.
And other stuff.
--
EOS
output = convert_string input, backend: 'docbook'
assert_css 'abstract', output, 1
assert_css 'abstract > simpara', output, 2
end
test 'should make abstract on open block with title converted to DocBook' do
input = <<~'EOS'
= Article
.My abstract
[abstract]
--
This article is about stuff.
--
EOS
output = convert_string input, backend: 'docbook'
assert_css 'abstract', output, 1
assert_css 'abstract > title', output, 1
assert_css 'abstract > title + simpara', output, 1
end
test 'should allow abstract in document with title if doctype is book converted to DocBook' do
input = <<~'EOS'
= Book
:doctype: book
[abstract]
Abstract for book with title is valid
EOS
output = convert_string input, backend: 'docbook'
assert_css 'abstract', output, 1
end
test 'should not allow abstract as direct child of document if doctype is book converted to DocBook' do
input = <<~'EOS'
:doctype: book
[abstract]
Abstract for book is invalid.
EOS
output = convert_string input, backend: 'docbook'
assert_css 'abstract', output, 0
assert_message @logger, :WARN, 'abstract block cannot be used in a document without a title when doctype is book. Excluding block content.'
end
# TODO partintro shouldn't be recognized if doctype is not book, should be in proper place
test 'should accept partintro on open block without title' do
input = <<~'EOS'
= Book
:doctype: book
= Part 1
[partintro]
--
This is a part intro.
It can have multiple paragraphs.
--
== Chapter 1
content
EOS
output = convert_string input
assert_css '.openblock', output, 1
assert_css '.openblock.partintro', output, 1
assert_css '.openblock .title', output, 0
assert_css '.openblock .content', output, 1
assert_xpath %(//h1[@id="_part_1"]/following-sibling::*[#{contains_class :openblock}]), output, 1
assert_xpath %(//*[#{contains_class :openblock}]/*[@class="content"]/*[@class="paragraph"]), output, 2
end
test 'should accept partintro on open block with title' do
input = <<~'EOS'
= Book
:doctype: book
= Part 1
.Intro title
[partintro]
--
This is a part intro with a title.
--
== Chapter 1
content
EOS
output = convert_string input
assert_css '.openblock', output, 1
assert_css '.openblock.partintro', output, 1
assert_css '.openblock .title', output, 1
assert_css '.openblock .content', output, 1
assert_xpath %(//h1[@id="_part_1"]/following-sibling::*[#{contains_class :openblock}]), output, 1
assert_xpath %(//*[#{contains_class :openblock}]/*[@class="title"][text()="Intro title"]), output, 1
assert_xpath %(//*[#{contains_class :openblock}]/*[@class="content"]/*[@class="paragraph"]), output, 1
end
test 'should exclude partintro if not a child of part' do
input = <<~'EOS'
= Book
:doctype: book
[partintro]
part intro paragraph
EOS
output = convert_string input
assert_css '.partintro', output, 0
assert_message @logger, :ERROR, 'partintro block can only be used when doctype is book and must be a child of a book part. Excluding block content.'
end
test 'should not allow partintro unless doctype is book' do
input = <<~'EOS'
[partintro]
part intro paragraph
EOS
output = convert_string input
assert_css '.partintro', output, 0
assert_message @logger, :ERROR, 'partintro block can only be used when doctype is book and must be a child of a book part. Excluding block content.'
end
test 'should accept partintro on open block without title converted to DocBook' do
input = <<~'EOS'
= Book
:doctype: book
= Part 1
[partintro]
--
This is a part intro.
It can have multiple paragraphs.
--
== Chapter 1
content
EOS
output = convert_string input, backend: 'docbook'
assert_css 'partintro', output, 1
assert_css 'part[xml|id="_part_1"] > partintro', output, 1
assert_css 'partintro > simpara', output, 2
end
test 'should accept partintro on open block with title converted to DocBook' do
input = <<~'EOS'
= Book
:doctype: book
= Part 1
.Intro title
[partintro]
--
This is a part intro with a title.
--
== Chapter 1
content
EOS
output = convert_string input, backend: 'docbook'
assert_css 'partintro', output, 1
assert_css 'part[xml|id="_part_1"] > partintro', output, 1
assert_css 'partintro > title', output, 1
assert_css 'partintro > title + simpara', output, 1
end
test 'should exclude partintro if not a child of part converted to DocBook' do
input = <<~'EOS'
= Book
:doctype: book
[partintro]
part intro paragraph
EOS
output = convert_string input, backend: 'docbook'
assert_css 'partintro', output, 0
assert_message @logger, :ERROR, 'partintro block can only be used when doctype is book and must be a child of a book part. Excluding block content.'
end
test 'should not allow partintro unless doctype is book converted to DocBook' do
input = <<~'EOS'
[partintro]
part intro paragraph
EOS
output = convert_string input, backend: 'docbook'
assert_css 'partintro', output, 0
assert_message @logger, :ERROR, 'partintro block can only be used when doctype is book and must be a child of a book part. Excluding block content.'
end
end
context 'Substitutions' do
test 'processor should not crash if subs are empty' do
input = <<~'EOS'
[subs=","]
....
content
....
EOS
doc = document_from_string input
block = doc.blocks.first
assert_empty block.subs
end
test 'should be able to append subs to default block substitution list' do
input = <<~'EOS'
:application: Asciidoctor
[subs="+attributes,+macros"]
....
{application}
....
EOS
doc = document_from_string input
block = doc.blocks.first
assert_equal [:specialcharacters, :attributes, :macros], block.subs
end
test 'should be able to prepend subs to default block substitution list' do
input = <<~'EOS'
:application: Asciidoctor
[subs="attributes+"]
....
{application}
....
EOS
doc = document_from_string input
block = doc.blocks.first
assert_equal [:attributes, :specialcharacters], block.subs
end
test 'should be able to remove subs to default block substitution list' do
input = <<~'EOS'
[subs="-quotes,-replacements"]
content
EOS
doc = document_from_string input
block = doc.blocks.first
assert_equal [:specialcharacters, :attributes, :macros, :post_replacements], block.subs
end
test 'should be able to prepend, append and remove subs from default block substitution list' do
input = <<~'EOS'
:application: asciidoctor
[subs="attributes+,-verbatim,+specialcharacters,+macros"]
....
https://{application}.org[{gt}{gt}] <1>
....
EOS
doc = document_from_string input, standalone: false
block = doc.blocks.first
assert_equal [:attributes, :specialcharacters, :macros], block.subs
result = doc.convert
assert_includes result, '<pre><a href="https://asciidoctor.org">>></a> <1></pre>'
end
test 'should be able to set subs then modify them' do
input = <<~'EOS'
[subs="verbatim,-callouts"]
_hey now_ <1>
EOS
doc = document_from_string input, standalone: false
block = doc.blocks.first
assert_equal [:specialcharacters], block.subs
result = doc.convert
assert_includes result, '_hey now_ <1>'
end
end
context 'References' do
test 'should not recognize block anchor with illegal id characters' do
input = <<~'EOS'
[[illegal$id,Reference Text]]
----
content
----
EOS
doc = document_from_string input
block = doc.blocks.first
assert_nil block.id
assert_nil block.attr 'reftext'
refute doc.catalog[:refs].key? 'illegal$id'
end
test 'should not recognize block anchor that starts with digit' do
input = <<~'EOS'
[[3-blind-mice]]
--
see how they run
--
EOS
output = convert_string_to_embedded input
assert_includes output, '[[3-blind-mice]]'
assert_xpath '/*[@id=":3-blind-mice"]', output, 0
end
test 'should recognize block anchor that starts with colon' do
input = <<~'EOS'
[[:idname]]
--
content
--
EOS
output = convert_string_to_embedded input
assert_xpath '/*[@id=":idname"]', output, 1
end
test 'should use specified id and reftext when registering block reference' do
input = <<~'EOS'
[[debian,Debian Install]]
.Installation on Debian
----
$ apt-get install asciidoctor
----
EOS
doc = document_from_string input
ref = doc.catalog[:refs]['debian']
refute_nil ref
assert_equal 'Debian Install', ref.reftext
assert_equal 'debian', (doc.resolve_id 'Debian Install')
end
test 'should allow square brackets in block reference text' do
input = <<~'EOS'
[[debian,[Debian] Install]]
.Installation on Debian
----
$ apt-get install asciidoctor
----
EOS
doc = document_from_string input
ref = doc.catalog[:refs]['debian']
refute_nil ref
assert_equal '[Debian] Install', ref.reftext
assert_equal 'debian', (doc.resolve_id '[Debian] Install')
end
test 'should allow comma in block reference text' do
input = <<~'EOS'
[[debian, Debian, Ubuntu]]
.Installation on Debian
----
$ apt-get install asciidoctor
----
EOS
doc = document_from_string input
ref = doc.catalog[:refs]['debian']
refute_nil ref
assert_equal 'Debian, Ubuntu', ref.reftext
assert_equal 'debian', (doc.resolve_id 'Debian, Ubuntu')
end
test 'should resolve attribute reference in title using attribute defined at location of block' do
input = <<~'EOS'
= Document Title
:foo: baz
intro paragraph. see <<free-standing>>.
:foo: bar
.foo is {foo}
[#formal-para]
paragraph with title
[discrete#free-standing]
== foo is still {foo}
EOS
doc = document_from_string input
ref = doc.catalog[:refs]['formal-para']
refute_nil ref
assert_equal 'foo is bar', ref.title
assert_equal 'formal-para', (doc.resolve_id 'foo is bar')
output = doc.convert standalone: false
assert_include '<a href="#free-standing">foo is still bar</a>', output
assert_include '<h2 id="free-standing" class="discrete">foo is still bar</h2>', output
end
test 'should substitute attribute references in reftext when registering block reference' do
input = <<~'EOS'
:label-tiger: Tiger
[[tiger-evolution,Evolution of the {label-tiger}]]
****
Information about the evolution of the tiger.
****
EOS
doc = document_from_string input
ref = doc.catalog[:refs]['tiger-evolution']
refute_nil ref
assert_equal 'Evolution of the Tiger', ref.attributes['reftext']
assert_equal 'tiger-evolution', (doc.resolve_id 'Evolution of the Tiger')
end
test 'should use specified reftext when registering block reference' do
input = <<~'EOS'
[[debian]]
[reftext="Debian Install"]
.Installation on Debian
----
$ apt-get install asciidoctor
----
EOS
doc = document_from_string input
ref = doc.catalog[:refs]['debian']
refute_nil ref
assert_equal 'Debian Install', ref.reftext
assert_equal 'debian', (doc.resolve_id 'Debian Install')
end
end
end
| 32.956642 | 556 | 0.625942 |
264ea8798c208953fe75ba157287d9b891cbccf1 | 2,224 | # ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# Please read more about how to change this file in README.md and
# CONTRIBUTING.md located at the root of this package.
#
# ----------------------------------------------------------------------------
title 'Test GCP google_compute_url_map resource.'
gcp_project_id = attribute(:gcp_project_id, default: 'gcp_project_id', description: 'The GCP project identifier.')
url_map = attribute('url_map', default: {
"name": "inspec-gcp-url-map",
"description": "URL map description",
"host_rule_host": "site.com",
"path_matcher_name": "allpaths",
"path_rule_path": "/home",
"test_host": "test.com",
"test_path": "/home"
}, description: 'Compute URL map definition')
backend_service = attribute('backend_service', default: {
"name": "inspec-gcp-backend-service",
"description": "A description",
"port_name": "http",
"protocol": "HTTP",
"timeout_sec": 10,
"enable_cdn": true
}, description: 'Backend service definition')
control 'google_compute_url_map-1.0' do
impact 1.0
title 'google_compute_url_map resource test'
describe google_compute_url_map(project: gcp_project_id, name: url_map['name']) do
it { should exist }
its('description') { should eq url_map['description'] }
its('default_service') { should match /\/inspec-gcp-backend-service$/ }
its('host_rules.count') { should eq 1 }
its('host_rules.first.hosts') { should include url_map['host_rule_host'] }
its('path_matchers.count') { should eq 1 }
its('path_matchers.first.default_service') { should match /\/inspec-gcp-backend-service$/ }
its('tests.count') { should eq 1 }
its('tests.first.host') { should eq url_map['test_host'] }
its('tests.first.path') { should eq url_map['test_path'] }
end
describe google_compute_url_map(project: gcp_project_id, name: 'nonexistent') do
it { should_not exist }
end
end
| 39.714286 | 114 | 0.622752 |
5d8823583c15de3a5b28a62e6006699aa31e638e | 10,218 | RSpec.describe MiqWidgetSet do
let(:group) { user.current_group }
let(:user) { FactoryBot.create(:user_with_group) }
let(:miq_widget) { FactoryBot.create(:miq_widget) }
before do
@ws_group = FactoryBot.create(:miq_widget_set, :name => 'Home', :owner => group)
end
context ".seed" do
include_examples ".seed called multiple times"
let(:yaml_attributes) do
{
"name" => "default",
"read_only" => "t",
"set_type" => "MiqWidgetSet",
"description" => "Default Dashboard",
"set_data_by_description" => {
'col1' => [
miq_widget.description
]
}
}
end
it "creates widget set from yaml even when another widget set with same name exist" do
Tempfile.create do |yml_file|
yml_file.write(yaml_attributes.to_yaml)
yml_file.flush
FactoryBot.create(:miq_widget_set, :name => "default", :updated_on => File.mtime(yml_file).utc - 1.day)
expect(MiqWidgetSet.find_by(:name => 'default', :userid => nil, :group_id => nil)).to be_nil
expect do
MiqWidgetSet.sync_from_file(yml_file)
end.to change(MiqWidgetSet, :count).by(1)
expect(MiqWidgetSet.find_by(:name => 'default', :userid => nil, :group_id => nil)).not_to be_nil
end
end
end
describe "validate" do
it "validates that MiqWidgetSet#name cannot contain \"|\" " do
widget_set = MiqWidgetSet.create(:name => 'TEST|TEST')
expect(widget_set.errors[:name]).to include("cannot contain \"|\"")
end
let(:other_group) { FactoryBot.create(:miq_group) }
it "validates that MiqWidgetSet has unique description per group and userid" do
widget_set = MiqWidgetSet.create(:description => @ws_group.description, :owner => group)
expect(widget_set.errors[:description]).to include("must be unique for this group and userid")
widget_set = MiqWidgetSet.create(:description => @ws_group.description, :owner => nil)
expect(widget_set.errors[:description]).not_to include("must be unique for this group and userid")
widget_set = MiqWidgetSet.create(:description => @ws_group.description, :owner => other_group)
expect(widget_set.errors[:description]).not_to include("must be unique for this group and userid")
widget_set = MiqWidgetSet.create(:description => @ws_group.description, :owner => other_group)
expect(widget_set.errors[:description]).not_to include("must be unique for this group and userid")
FactoryBot.create(:miq_widget_set, :description => @ws_group.description, :owner => other_group, :userid => "x")
FactoryBot.create(:miq_widget_set, :description => @ws_group.description, :owner => other_group, :userid => "y")
other_userids = MiqWidgetSet.where(:description => @ws_group.description, :owner => other_group).map(&:userid)
expect(other_userids).to match_array(%w[x y])
other_widget_set = MiqWidgetSet.create(:description => @ws_group.description, :owner => other_group, :userid => "x")
expect(other_widget_set.errors[:description]).to include("must be unique for this group and userid")
end
it "validates that there is at least one widget in set_data" do
widget_set = MiqWidgetSet.create
expect(widget_set.errors[:set_data]).to include("One widget must be selected(set_data)")
end
it "validates that widgets in set_data have to exist" do
unknown_id = MiqWidgetSet.maximum(:id) + 1
widget_set = MiqWidgetSet.create(:set_data => {:col1 => [unknown_id]})
expect(widget_set.errors[:set_data]).to include("Unable to find widget ids: #{unknown_id}")
end
it "validates that group_id has to be present for non-read_only widget sets" do
widget_set = MiqWidgetSet.create(:read_only => false)
expect(widget_set.errors[:group_id]).to include("can't be blank")
widget_set = MiqWidgetSet.create(:read_only => true)
expect(widget_set.errors[:group_id]).not_to include("can't be blank")
end
it "works with HashWithIndifferentAccess set_data" do
widget_set = MiqWidgetSet.create(:set_data => HashWithIndifferentAccess.new({:col1 => []}))
expect(widget_set.errors[:set_data]).to include("One widget must be selected(set_data)")
end
end
it "when a group dashboard is deleted" do
expect(MiqWidgetSet.count).to eq(1)
@ws_group.destroy
expect(MiqWidgetSet.count).to eq(0)
end
context "with a group" do
it "being deleted" do
expect(MiqWidgetSet.count).to eq(1)
user.destroy
group.destroy
expect(MiqWidgetSet.count).to eq(0)
end
end
context "with a user" do
before do
FactoryBot.create(:miq_widget_set, :name => 'Home', :userid => user.userid, :group_id => group.id)
end
it "initial state" do
expect(MiqWidgetSet.count).to eq(2)
end
it "the belong to group is being deleted" do
expect { expect { group.destroy! }.to raise_error(ActiveRecord::RecordNotDestroyed) }.to_not(change { MiqWidgetSet.count })
expect(group.errors[:base]).to include("The group has users assigned that do not belong to any other group")
end
it "being deleted" do
user.destroy
expect(MiqWidgetSet.count).to eq(1)
end
end
describe ".destroy_user_versions" do
before do
FactoryBot.create(:miq_widget_set, :name => 'User_Home', :userid => user.userid, :owner => group)
end
it "destroys all user's versions of dashboards (dashboards been customized by user)" do
expect(MiqWidgetSet.count).to eq(2)
MiqWidgetSet.destroy_user_versions
expect(MiqWidgetSet.count).to eq(1)
expect(MiqWidgetSet.first).to eq(@ws_group)
end
end
describe "#where_unique_on" do
let(:group2) { FactoryBot.create(:miq_group, :description => 'dev group2') }
let(:ws_1) { FactoryBot.create(:miq_widget_set, :name => 'Home', :userid => user.userid, :owner => group, :group_id => group.id) }
before do
user.miq_groups << group2
ws_1
FactoryBot.create(:miq_widget_set, :name => 'Home', :userid => user.userid, :owner => group2, :group_id => group2.id)
end
it "initial state" do
expect(MiqWidgetSet.count).to eq(3)
end
it "brings back all group records" do
expect(MiqWidgetSet.where_unique_on('Home')).to eq([@ws_group])
end
it "brings back records for a user with a group" do
expect(MiqWidgetSet.where_unique_on('Home', user)).to eq([ws_1])
end
end
describe "#with_users" do
it "brings back records with users" do
ws = FactoryBot.create(:miq_widget_set, :name => 'Home', :userid => user.userid, :group_id => group.id)
expect(described_class.with_users).to eq([ws])
end
end
context ".with_array_order" do
it "returns in index order" do
g1 = FactoryBot.create(:miq_widget_set)
g2 = FactoryBot.create(:miq_widget_set)
expect(MiqWidgetSet.where(:id => [g1.id, g2.id]).with_array_order([g1.id.to_s, g2.id.to_s])).to eq([g1, g2])
end
it "returns in non index order" do
g1 = FactoryBot.create(:miq_widget_set)
g2 = FactoryBot.create(:miq_widget_set)
expect(MiqWidgetSet.where(:id => [g1.id, g2.id]).with_array_order([g2.id.to_s, g1.id.to_s])).to eq([g2, g1])
end
end
context "loading group specific defaul dashboard" do
let!(:miq_widget_set) { FactoryBot.create(:miq_widget, :description => 'chart_vendor_and_guest_os') }
describe ".sync_from_file" do
let(:dashboard_name) { "Dashboard for Group" }
before do
@yml_file = Tempfile.new('default_dashboard_for_group.yaml')
yml_data = YAML.safe_load(<<~DOC, [Symbol])
---
name: #{dashboard_name}
read_only: t
set_type: MiqWidgetSet
description: Test Dashboard for Group
owner_type: MiqGroup
owner_description: #{group.description}
set_data_by_description:
:col1:
- chart_vendor_and_guest_os
DOC
File.write(@yml_file.path, yml_data.to_yaml)
end
after do
@yml_file.close(true)
end
it "loads dashboard for specific group" do
described_class.sync_from_file(@yml_file.path)
dashboard = MiqWidgetSet.find_by(:name => dashboard_name)
expect(dashboard.owner_id).to eq(group.id)
end
end
end
describe ".copy_dashboard" do
let(:name) { "New Dashboard Name" }
let(:tab) { "Dashboard Tab" }
let(:other_group) { FactoryBot.create(:miq_group) }
it "does not raises error if the same dashboard name used for different groups" do
expect { MiqWidgetSet.copy_dashboard(@ws_group, @ws_group.name, tab, other_group.id) }.not_to raise_error
end
it "raises error if passed tab name is empty" do
expect { MiqWidgetSet.copy_dashboard(@ws_group, name, "") }.to raise_error(ActiveRecord::RecordInvalid, "Validation failed: MiqWidgetSet: Description can't be blank")
end
it "raises error if group with passed id does not exist" do
expect { MiqWidgetSet.copy_dashboard(@ws_group, name, tab, "9999") }.to raise_error(ActiveRecord::RecordNotFound, "Couldn't find MiqGroup with 'id'=9999")
end
it "copy dashboard and set its owner to the group with passed group_id" do
another_group = FactoryBot.create(:miq_group, :description => 'some_group')
MiqWidgetSet.copy_dashboard(@ws_group, name, tab, another_group.id)
dashboard = MiqWidgetSet.find_by(:owner_id => another_group.id)
expect(dashboard.name).to eq(name)
end
it "copy dashboard and set its owner to the same group if no group_id parameter passed" do
expect(MiqWidgetSet.where(:owner_id => group.id).count).to eq(1)
dashboard = MiqWidgetSet.copy_dashboard(@ws_group, name, tab)
expect(MiqWidgetSet.find_by(:owner_id => group.id, :name => name)).to eq dashboard
end
it "keeps the same set of widgets and dashboard's settings" do
new_dashboard = MiqWidgetSet.copy_dashboard(@ws_group, name, tab)
expect(new_dashboard.set_data).to eq @ws_group.set_data
end
end
end
| 38.126866 | 172 | 0.669211 |
3344ff80bfadc344ba3ee7ac168bf3063cd2f0b7 | 926 | module Fog
module Compute
class OpenStack
class Real
def list_servers(options = {})
params = options.dup
if params[:all_tenants]
params['all_tenants'] = 'True'
params.delete(:all_tenants)
end
request(
:expects => [200, 203],
:method => 'GET',
:path => 'servers.json',
:query => params
)
end
end
class Mock
def list_servers(options = {})
response = Excon::Response.new
data = list_servers_detail.body['servers']
servers = []
for server in data
servers << server.reject { |key, value| !['id', 'name', 'links'].include?(key) }
end
response.status = [200, 203][rand(1)]
response.body = { 'servers' => servers }
response
end
end
end
end
end
| 25.027027 | 92 | 0.481641 |
33988a5afd2cfacbfe8b5891484ca042990ccbca | 1,556 | class ApplicationController < ActionController::Base
include Concerns::Event
protect_from_forgery with: :exception
if ENV['HTTP_BASIC_AUTH_ENABLED'] == 'true'
http_basic_authenticate_with name: ENV['HTTP_BASIC_AUTH_NAME'], password: ENV['HTTP_BASIC_AUTH_PASSWORD']
end
before_action :authenticate_user!
before_action :store_return_to_path, only: :index
before_action :deep_strip_params, only: :index
rescue_from CanCan::AccessDenied do |e|
redirect_to root_url, flash: { error: e.message }
end
rescue_from ActiveRecord::RecordNotFound do |e|
redirect_to root_url, flash: { error: e.message }
end
private
def store_return_to_path
session[:return_to] = {} if session[:return_to].blank?
session[:return_to][request.params[:controller]] = request.fullpath unless request.fullpath.include?('.json')
end
def deep_strip_params
params.each_pair do |k, v|
if v.is_a?(Hash) || v.is_a?(ActionController::Parameters)
deep_strip_params!(v)
elsif v.is_a?(Array)
v.each_with_index do |v2, index|
v[index] = v2.squish
end
else
params[k] = v.to_s.squish
end
end
end
def deep_strip_params!(hash)
hash.each_pair do |k, v|
if v.is_a?(Array)
v.each_with_index do |v2, index|
v[index] = v2.squish
end
else
hash[k] = v.squish
end
end
end
def after_sign_in_path_for(resource)
if current_user.present? && current_user.is_admin?
admin_companies_path
end
end
end
| 24.698413 | 113 | 0.678021 |
ffe52011ba32a0db48d9b5d48009cfdd5f12b332 | 93 | # frozen_string_literal: true
class Ledger < ActiveRecord::Base
has_one_keepr_account
end
| 15.5 | 33 | 0.817204 |
910c1c0c10528c6bb88db9b7cd4757f2345bf773 | 599 | require File.expand_path('../../../../../spec_helper', __FILE__)
require 'net/http'
require File.expand_path('../fixtures/http_server', __FILE__)
describe "Net::HTTP#copy" do
before(:all) do
NetHTTPSpecs.start_server
end
after(:all) do
NetHTTPSpecs.stop_server
end
before(:each) do
@http = Net::HTTP.start("127.0.0.1", NetHTTPSpecs.server_port)
end
it "sends a COPY request to the passed path and returns the response" do
response = @http.copy("/request")
response.should be_kind_of(Net::HTTPResponse)
response.body.should == "Request type: COPY"
end
end
| 24.958333 | 74 | 0.69616 |
6ab8badb5aecb17e2810ac5e8ce0c68e776f2bd5 | 1,252 | # Copyright 2015 Google 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.
require 'google/apis/dlp_v2/service.rb'
require 'google/apis/dlp_v2/classes.rb'
require 'google/apis/dlp_v2/representations.rb'
module Google
module Apis
# Cloud Data Loss Prevention (DLP) API
#
# Provides methods for detection, risk analysis, and de-identification of
# privacy-sensitive fragments in text, images, and Google Cloud Platform storage
# repositories.
#
# @see https://cloud.google.com/dlp/docs/
module DlpV2
VERSION = 'V2'
REVISION = '20191206'
# View and manage your data across Google Cloud Platform services
AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
end
end
end
| 33.837838 | 84 | 0.731629 |
1dad5c6269897d476e0308c25bf711df45c94283 | 306 | class NotificationSerializer < ActiveModel::Serializer
attributes :id, :actor, :content_type, :content, :read, :read_at, :created_at, :updated_at, :notification_text
has_one :actor, serializer: SimpleUserSerializer
def notification_text
object.content.notification_text(object.actor)
end
end
| 30.6 | 112 | 0.787582 |
d5f9ab93e249a30711409f291028c84e906af761 | 1,974 | # frozen_string_literal: true
# We have already seen how to define an outline tree sequentially.
#
# If you'd like to add nodes to the middle of an outline tree the
# <code>add_subsection_to</code> may help you.
#
# It allows you to insert sections to the outline tree at any point. Just
# provide the <code>title</code> of the parent section, the
# <code>position</code> you want the new subsection to be inserted
# <code>:first</code> or <code>:last</code> (defaults to <code>:last</code>)
# and a block to declare the subsection.
#
# The <code>add_subsection_to</code> block doesn't necessarily create new
# sections, it may also create new pages.
#
# If the parent title provided is the title of a page. The page will be
# converted into a section to receive the subsection created.
require_relative '../example_helper'
filename = File.basename(__FILE__).gsub('.rb', '.pdf')
Prawn::ManualBuilder::Example.generate(filename) do
# First we create 10 pages and some default outline
(1..10).each do |index|
text "Page #{index}"
start_new_page
end
outline.define do
section('Section 1', destination: 1) do
page title: 'Page 2', destination: 2
page title: 'Page 3', destination: 3
end
end
# Now we will start adding nodes to the previous outline
outline.add_subsection_to('Section 1', :first) do
outline.section('Added later - first position') do
outline.page title: 'Page 4', destination: 4
outline.page title: 'Page 5', destination: 5
end
end
outline.add_subsection_to('Section 1') do
outline.page title: 'Added later - last position',
destination: 6
end
outline.add_subsection_to('Added later - first position') do
outline.page title: 'Another page added later',
destination: 7
end
# The title provided is for a page which will be converted into a section
outline.add_subsection_to('Page 3') do
outline.page title: 'Last page added',
destination: 8
end
end
| 32.360656 | 76 | 0.711246 |
bf9d9141a97927de7428b44ac1a92beb475a9352 | 6,069 | module ActiveFedora
module Indexing
class FieldMapper
class_attribute :id_field, :descriptors
# set defaults
self.id_field = 'id'
self.descriptors = [DefaultDescriptors]
# @api
# @params [Hash] doc the hash to insert the value into
# @params [String] name the name of the field (without the suffix)
# @params [String,Date] value the value to be inserted
# @params [Array,Hash] indexer_args the arguments that find the indexer
# @returns [Hash] doc the document that was provided with the new field (replacing any field with the same name)
def set_field(doc, name, value, *indexer_args)
# adding defaults indexer
indexer_args = [:stored_searchable] if indexer_args.empty?
doc.merge! solr_names_and_values(name, value, indexer_args)
doc
end
# @api
# Given a field name, index_type, etc., returns the corresponding Solr name.
# TODO field type is the input format, maybe we could just detect that?
# See https://github.com/samvera/active_fedora/issues/1338
# @param [String] field_name the ruby (term) name which will get a suffix appended to become a Solr field name
# @param opts - index_type is only needed if the FieldDescriptor requires it (e.g. :searcahble)
# @return [String] name of the solr field, based on the params
def solr_name(field_name, *opts)
index_type, args = if opts.first.is_a? Hash
[:stored_searchable, opts.first]
elsif opts.empty?
[:stored_searchable, { type: :text }]
else
[opts[0], opts[1] || { type: :string }]
end
indexer(index_type).name_and_converter(field_name, args).first
end
# Given a field name-value pair, a data type, and an array of index types, returns a hash of
# mapped names and values. The values in the hash are _arrays_, and may contain multiple values.
def solr_names_and_values(field_name, field_value, index_types)
return {} if field_value.nil?
# Determine the set of index types
index_types = Array(index_types)
index_types.uniq!
index_types.dup.each do |index_type|
if index_type.to_s =~ /^not_(.*)/
index_types.delete index_type # not_foo
index_types.delete Regexp.last_match(1).to_sym # foo
end
end
# Map names and values
results = {}
# Time seems to extend enumerable, so wrap it so we don't interate over each of its elements.
field_value = [field_value] if field_value.is_a? Time
index_types.each do |index_type|
Array(field_value).each do |single_value|
# Get mapping for field
descriptor = indexer(index_type)
data_type = extract_type(single_value)
name, converter = descriptor.name_and_converter(field_name, type: data_type)
next unless name
# Is there a custom converter?
# TODO instead of a custom converter, look for input data type and output data type. Create a few methods that can do that cast.
# See https://github.com/samvera/active_fedora/issues/1339
value = if converter
if converter.arity == 1
converter.call(single_value)
else
converter.call(single_value, field_name)
end
elsif data_type == :boolean
single_value
else
single_value.to_s
end
# Add mapped name & value, unless it's a duplicate
if descriptor.evaluate_suffix(data_type).multivalued?
values = (results[name] ||= [])
values << value unless value.nil? || values.include?(value)
else
Rails.logger.warn "Setting #{name} to `#{value}', but it already had `#{results[name]}'" if results[name]
results[name] = value
end
end
end
results
end
private
# @param [Symbol, String, Descriptor] index_type is a Descriptor, a symbol that references a method that returns a Descriptor, or a string which will be used as the suffix.
# @return [Descriptor]
def indexer(index_type)
index_type = case index_type
when Symbol
index_type_macro(index_type)
when String
StringDescriptor.new(index_type)
when Descriptor
index_type
else
raise InvalidIndexDescriptor, "#{index_type.class} is not a valid indexer_type. Use a String, Symbol or Descriptor."
end
raise InvalidIndexDescriptor, "index type should be an Descriptor, you passed: #{index_type.class}" unless index_type.is_a? Descriptor
index_type
end
# @param index_type [Symbol]
# search through the descriptors (class attribute) until a module is found that responds to index_type, then call it.
def index_type_macro(index_type)
klass = self.class.descriptors.find { |descriptor_klass| descriptor_klass.respond_to? index_type }
if klass
klass.send(index_type)
else
raise UnknownIndexMacro, "Unable to find `#{index_type}' in #{self.class.descriptors}"
end
end
def extract_type(value)
case value
when NilClass
nil
when Integer # In ruby < 2.4, Fixnum extends Integer
:integer
when DateTime
:time
when TrueClass, FalseClass
:boolean
else
value.class.to_s.underscore.to_sym
end
end
end
end
end
| 40.731544 | 180 | 0.585269 |
bb9ac375b9465a7e9a4d640104550aab64a22a99 | 327 | class CdrController < Controller
def post
uuid, xml, leg = request['uuid', 'cdr', 'leg']
xml = CGI.unescape(xml) if xml[0, 9] == '%3C%3Fxml'
call = TinyCdr::Call.create_from_xml(uuid, xml, leg)
Ramaze::Log.info "New call from #{call.username || call.caller_id_number} to #{call.destination_number}"
end
end
| 36.333333 | 108 | 0.669725 |
01f3e3672f79356c14b12e185dc207c21a91516b | 1,750 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20140516191259) do
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "encrypted_otp_secret"
t.string "encrypted_otp_secret_iv"
t.string "encrypted_otp_secret_salt"
t.integer "consumed_timestep"
t.boolean "otp_required_for_login"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
| 43.75 | 104 | 0.730857 |
1c55e796508d0162ce149c3fea072d477137760d | 992 | # Programming Languages, Dan Grossman
# Section 7: Subclassing
class Point
attr_accessor :x, :y
def initialize(x,y)
@x = x
@y = y
end
def distFromOrigin
Math.sqrt(@x * @x + @y * @y) # why a module method? Less OOP :-(
end
def distFromOrigin2
Math.sqrt(x * x + y * y) # uses getter methods
end
end
class ColorPoint < Point
attr_accessor :color
def initialize(x,y,c="clear") # or could skip this and color starts unset
super(x,y) # keyword super calls same method in superclass
@color = c
end
end
# example uses with reflection
p = Point.new(0,0)
cp = ColorPoint.new(0,0,"red")
p.class # Point
p.class.superclass # Object
cp.class # ColorPoint
cp.class.superclass # Point
cp.class.superclass.superclass # Object
cp.is_a? Point # true
cp.instance_of? Point # false
cp.is_a? ColorPoint # true
cp.instance_of? ColorPoint # true
| 24.195122 | 75 | 0.606855 |
ab9751023cde58e1cfa9a607b4ad322305b8e75b | 3,186 | require 'devise'
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
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
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# 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
# Limits the available syntax to the non-monkey patched syntax that is recommended.
# For more details, see:
# - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
# - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| 43.643836 | 129 | 0.736974 |
ed2ea8e20e4767199c4fa5bdb11c54bd5f2c799e | 753 | class YoutubeUrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
@record = record
@attribute = attribute
@value = value
if value.present?
code = response_code(parsed_url)
record_error("is not valid. Please check it and try again.") unless code == 200
end
end
private
def record_error(msg)
@record.errors[@attribute] << msg
end
def parsed_url
uri = URI.parse(@value)
if uri.host == "www.youtube.com" && uri.scheme == "https"
uri.to_s
end
rescue URI::InvalidURIError
nil
end
def response_code(url = nil)
return if url.nil?
begin
RestClient.get(url).code
rescue RestClient::Exception => e
e.http_code
end
end
end
| 20.351351 | 85 | 0.654714 |
39d93c85b7660f4236739feda346963e7e427b14 | 574 | # rubocop:disable Layout/LineLength
require './item'
# Create class Book
class Book < Item
attr_accessor :publisher, :cover_state
attr_reader :publish_date
def initialize(publisher, cover_state, publish_date)
super(publish_date)
@publisher = publisher
@cover_state = cover_state
end
def to_s
"Publisher\'s name : \"#{@publisher}\" ~ Published on : #{@publish_date} ~ Cover state: #{cover_state ? 'Good state' : 'Bad state'}"
end
private
def can_be_archived?
@cover_state == 'bad' || super
end
end
# rubocop:enable Layout/LineLength
| 22.96 | 136 | 0.702091 |
7aa779c2094133d7a82366e977ce4d1e8b83dbd8 | 4,936 | # This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
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
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
TEST_DIR = Dir.getwd + '/__test_files__'
| 47.92233 | 92 | 0.742504 |
b9496b84993c263ca9f26aef8ba043fb4b375cb6 | 1,000 | # encoding: utf-8
module FriendlyId::NonSluggableInstanceMethods
attr :found_using_friendly_id
# Was the record found using one of its friendly ids?
def found_using_friendly_id?
@found_using_friendly_id
end
# Was the record found using its numeric id?
def found_using_numeric_id?
!@found_using_friendly_id
end
alias has_better_id? found_using_numeric_id?
# Returns the friendly_id.
def friendly_id
send friendly_id_options[:column]
end
alias best_id friendly_id
# Returns the friendly id, or if none is available, the numeric id.
def to_param
(friendly_id || id).to_s
end
private
def validate_friendly_id
if self.class.friendly_id_options[:reserved].include? friendly_id
self.errors.add(self.class.friendly_id_options[:column],
self.class.friendly_id_options[:reserved_message] % friendly_id)
return false
end
end
def found_using_friendly_id=(value) #:nodoc#
@found_using_friendly_id = value
end
end
| 22.727273 | 72 | 0.747 |
79cc2d15b9c9a472c300a72fafec71223a988a39 | 1,624 | # TODO: handle fields & fieldGroup
# TODO: make original response available
# TODO: specs
require 'httparty'
require 'ostruct'
require 'plissken'
require 'flyticket/ticketfly_error'
require 'flyticket/util'
module Flyticket
class Endpoint
include HTTParty
# Returns the key used to get the list of entries from Ticketfly's response.
def self.key
base_uri.split('/').last
end
# Gets many events
def self.get_many(fragment, options)
response = get fragment, query: query_string(options)
handle_error(response)
response[key].map { |hash| objectify(hash) }
end
# Gets a single event
def self.get_one(fragment, options)
response = get fragment, query: query_string(options)
handle_error(response)
objectify response[key].first
end
private
# Camelcases the given options hash.
def self.query_string(options)
options.map { |k, v| [Util.camelize(k, false), v] }.to_h
end
# Converts keys to snake case, then "semi-recursively" converts to OpenStruct.
def self.objectify(hash)
hash = hash.to_snake_keys
to_struct(hash, :venue)
to_struct(hash, :org)
OpenStruct.new(hash)
end
# Replaces a nested hash with a struct, given the parent hash and key.
def self.to_struct(hash, key)
return unless hash.has_key? key
hash[key] = OpenStruct.new(hash[key])
end
# Raises an error if the response indicates a problem.
def self.handle_error(response)
if response['status'] == 'error'
raise TicketflyError.new(response)
end
end
end
end
| 24.238806 | 82 | 0.674877 |
1cbc986cd8d73375a26b5a6d9008bec7390d4a34 | 6,274 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# Source: google/privacy/dlp/v2/dlp.proto for package 'google.privacy.dlp.v2'
# Original file comments:
# Copyright 2018 Google 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.
#
require 'grpc'
require 'google/privacy/dlp/v2/dlp_pb'
module Google
module Privacy
module Dlp
module V2
module DlpService
# The Cloud Data Loss Prevention (DLP) API is a service that allows clients
# to detect the presence of Personally Identifiable Information (PII) and other
# privacy-sensitive data in user-supplied, unstructured data streams, like text
# blocks or images.
# The service also includes methods for sensitive data redaction and
# scheduling of data scans on Google Cloud Platform based data sets.
class Service
include GRPC::GenericService
self.marshal_class_method = :encode
self.unmarshal_class_method = :decode
self.service_name = 'google.privacy.dlp.v2.DlpService'
# Finds potentially sensitive info in content.
# This method has limits on input size, processing time, and output size.
# [How-to guide for text](/dlp/docs/inspecting-text), [How-to guide for
# images](/dlp/docs/inspecting-images)
rpc :InspectContent, InspectContentRequest, InspectContentResponse
# Redacts potentially sensitive info from an image.
# This method has limits on input size, processing time, and output size.
# [How-to guide](/dlp/docs/redacting-sensitive-data-images)
rpc :RedactImage, RedactImageRequest, RedactImageResponse
# De-identifies potentially sensitive info from a ContentItem.
# This method has limits on input size and output size.
# [How-to guide](/dlp/docs/deidentify-sensitive-data)
rpc :DeidentifyContent, DeidentifyContentRequest, DeidentifyContentResponse
# Re-identifies content that has been de-identified.
rpc :ReidentifyContent, ReidentifyContentRequest, ReidentifyContentResponse
# Returns a list of the sensitive information types that the DLP API
# supports. For more information, see [Listing supported predefined
# infoTypes](/dlp/docs/listing-infotypes).
rpc :ListInfoTypes, ListInfoTypesRequest, ListInfoTypesResponse
# Creates an inspect template for re-using frequently used configuration
# for inspecting content, images, and storage.
rpc :CreateInspectTemplate, CreateInspectTemplateRequest, InspectTemplate
# Updates the inspect template.
rpc :UpdateInspectTemplate, UpdateInspectTemplateRequest, InspectTemplate
# Gets an inspect template.
rpc :GetInspectTemplate, GetInspectTemplateRequest, InspectTemplate
# Lists inspect templates.
rpc :ListInspectTemplates, ListInspectTemplatesRequest, ListInspectTemplatesResponse
# Deletes an inspect template.
rpc :DeleteInspectTemplate, DeleteInspectTemplateRequest, Google::Protobuf::Empty
# Creates a de-identify template for re-using frequently used configuration
# for Deidentifying content, images, and storage.
rpc :CreateDeidentifyTemplate, CreateDeidentifyTemplateRequest, DeidentifyTemplate
# Updates the de-identify template.
rpc :UpdateDeidentifyTemplate, UpdateDeidentifyTemplateRequest, DeidentifyTemplate
# Gets a de-identify template.
rpc :GetDeidentifyTemplate, GetDeidentifyTemplateRequest, DeidentifyTemplate
# Lists de-identify templates.
rpc :ListDeidentifyTemplates, ListDeidentifyTemplatesRequest, ListDeidentifyTemplatesResponse
# Deletes a de-identify template.
rpc :DeleteDeidentifyTemplate, DeleteDeidentifyTemplateRequest, Google::Protobuf::Empty
# Creates a job trigger to run DLP actions such as scanning storage for
# sensitive information on a set schedule.
rpc :CreateJobTrigger, CreateJobTriggerRequest, JobTrigger
# Updates a job trigger.
rpc :UpdateJobTrigger, UpdateJobTriggerRequest, JobTrigger
# Gets a job trigger.
rpc :GetJobTrigger, GetJobTriggerRequest, JobTrigger
# Lists job triggers.
rpc :ListJobTriggers, ListJobTriggersRequest, ListJobTriggersResponse
# Deletes a job trigger.
rpc :DeleteJobTrigger, DeleteJobTriggerRequest, Google::Protobuf::Empty
# Creates a new job to inspect storage or calculate risk metrics [How-to
# guide](/dlp/docs/compute-risk-analysis).
rpc :CreateDlpJob, CreateDlpJobRequest, DlpJob
# Lists DlpJobs that match the specified filter in the request.
rpc :ListDlpJobs, ListDlpJobsRequest, ListDlpJobsResponse
# Gets the latest state of a long-running DlpJob.
rpc :GetDlpJob, GetDlpJobRequest, DlpJob
# Deletes a long-running DlpJob. This method indicates that the client is
# no longer interested in the DlpJob result. The job will be cancelled if
# possible.
rpc :DeleteDlpJob, DeleteDlpJobRequest, Google::Protobuf::Empty
# Starts asynchronous cancellation on a long-running DlpJob. The server
# makes a best effort to cancel the DlpJob, but success is not
# guaranteed.
rpc :CancelDlpJob, CancelDlpJobRequest, Google::Protobuf::Empty
end
Stub = Service.rpc_stub_class
end
end
end
end
end
| 54.086207 | 105 | 0.687121 |
4aa66062a5d236f1c03dad6797ab11c132398e2d | 49 | require 'goldtweets'
require 'minitest/autorun'
| 12.25 | 26 | 0.795918 |
114860ba2616675ec2016f222ee3dbb992562516 | 98 | # typed: strict
# frozen_string_literal: true
class FakePackage < PackageSpec
export Yabba
end
| 14 | 31 | 0.785714 |
181dd566b6a5cb0d1bc72ad7178a4ca1c1876d42 | 279 | RSpec.describe Magick::Image, '#base_columns' do
it 'works' do
image = described_class.new(100, 100)
expect { image.base_columns }.not_to raise_error
expect(image.base_columns).to eq(0)
expect { image.base_columns = 1 }.to raise_error(NoMethodError)
end
end
| 27.9 | 67 | 0.716846 |
398899325d939276df39b1eb2fc8367c9314baeb | 2,798 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Monitor::Mgmt::V2016_03_01
module Models
#
# An alert incident indicates the activation status of an alert rule.
#
class Incident
include MsRestAzure
# @return [String] Incident name.
attr_accessor :name
# @return [String] Rule name that is associated with the incident.
attr_accessor :rule_name
# @return [Boolean] A boolean to indicate whether the incident is active
# or resolved.
attr_accessor :is_active
# @return [DateTime] The time at which the incident was activated in
# ISO8601 format.
attr_accessor :activated_time
# @return [DateTime] The time at which the incident was resolved in
# ISO8601 format. If null, it means the incident is still active.
attr_accessor :resolved_time
#
# Mapper for Incident class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Incident',
type: {
name: 'Composite',
class_name: 'Incident',
model_properties: {
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
rule_name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'ruleName',
type: {
name: 'String'
}
},
is_active: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'isActive',
type: {
name: 'Boolean'
}
},
activated_time: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'activatedTime',
type: {
name: 'DateTime'
}
},
resolved_time: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'resolvedTime',
type: {
name: 'DateTime'
}
}
}
}
}
end
end
end
end
| 28.55102 | 78 | 0.496069 |
0346b1f155f16b71b43a4b9537aa5ac3a4cdaab5 | 117 | # frozen_string_literal: true
module AlertManagement
def self.table_name_prefix
'alert_management_'
end
end
| 14.625 | 29 | 0.794872 |
08fc75ef4066efc2872bee50319107a2020dafaa | 1,641 | # frozen_string_literal: true
class AddSlackUserAndTeamIdToLeader < ActiveRecord::Migration[5.0]
SLACK_TEAM_ID = Rails.application.secrets.default_slack_team_id
def change
add_column :leaders, :slack_id, :text
add_column :leaders, :slack_team_id, :text
reversible do |change|
# Populate fields with slack usernames
change.up do
populate_slack_ids!
populate_slack_team_ids!
end
end
end
private
def populate_slack_ids!
return if select_all('SELECT * FROM leaders').empty?
leaders = select_all 'SELECT * FROM leaders '\
'WHERE slack_username IS NOT NULL AND '\
"slack_username != ''"
all_users ||= slack_list_users access_token
leaders.each do |leader|
slack_user = all_users.find { |u| u[:name] == leader['slack_username'] }
next if slack_user.nil?
update "UPDATE leaders SET slack_id = '#{slack_user[:id]}' "\
"WHERE slack_username = '#{leader['slack_username']}'"
end
end
def access_token
team = select_one 'SELECT * FROM hackbot_teams '\
"WHERE team_id = '#{SLACK_TEAM_ID}'"
team['bot_access_token']
end
def populate_slack_team_ids!
update "UPDATE leaders SET slack_team_id = '#{SLACK_TEAM_ID}'"
end
def slack_list_users(access_token)
resp = RestClient::Request.execute(
method: :post,
url: 'https://www.slack.com/api/users.list',
headers: {},
payload: {
token: access_token,
presence: true
}
)
JSON.parse(resp.body, symbolize_names: true)[:members]
end
end
| 25.246154 | 78 | 0.638635 |
1d3fa2afb956b04373b97ea832a50f4d83c3ac3a | 948 | module Spree
module TestingSupport
module Preferences
# Resets all preferences to default values, you can
# pass a block to override the defaults with a block
#
# reset_spree_preferences do |config|
# config.site_name = "my fancy pants store"
# end
#
def reset_spree_preferences(&config_block)
Spree::Preferences::Store.instance.persistence = false
Spree::Preferences::Store.instance.clear_cache
config = Rails.application.config.spree.preferences
configure_spree_preferences &config_block if block_given?
end
def configure_spree_preferences
config = Rails.application.config.spree.preferences
yield(config) if block_given?
end
def assert_preference_unset(preference)
find("#preferences_#{preference}")['checked'].should be false
Spree::Config[preference].should be false
end
end
end
end
| 29.625 | 69 | 0.682489 |
017be053783ec0d6a353d02123e8b6d9b60d4305 | 3,096 | require 'simplecov'
SimpleCov.start
if ENV["TRAVIS"] || ENV['CI']
require 'coveralls'
Coveralls.wear!('rails') { add_filter("/spec/") }
end
ENV["RAILS_ENV"] ||= 'test'
ENV["AUTOMATE_DOMAINS"] = "ManageIQ" # Reset only the ManageIQ automate domain when testing.
require File.expand_path('manageiq/config/environment', __dir__)
require 'rspec/rails'
def require_domain_file
spec_name = caller_locations(1..1).first.path
file_name = spec_name.sub("spec/", "").sub("_spec.rb", ".rb")
AutomateClassDefinitionHook.require_with_hook(file_name)
end
# Requires supporting ruby files
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
Dir[ManageIQ::AutomationEngine::Engine.root.join("spec/support/**/*.rb")].each { |f| require f }
Dir[ManageIQ::Content::Engine.root.join("spec/support/**/*.rb")].each { |f| require f }
RSpec.configure do |config|
config.include Spec::Support::AutomationHelper
config.include Spec::Support::RakeTaskExampleGroup, :type => :rake_task
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.use_instantiated_fixtures = false
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.mock_with :rspec do |c|
c.allow_message_expectations_on_nil = false
c.syntax = :expect
end
config.before(:suite) do
puts "** Resetting #{ENV["AUTOMATE_DOMAINS"]} domain(s)"
Tenant.seed
MiqAeDatastore.reset
MiqAeDatastore.reset_to_defaults
end
config.before do
EmsRefresh.try(:debug_failures=, true)
end
config.around(:each) do |ex|
begin
EvmSpecHelper.clear_caches { ex.run }
rescue SystemExit => e
STDERR.puts
STDERR.puts "Kernel.exit called from:"
STDERR.puts e.backtrace
exit 1
end
end
config.after(:suite) do
MiqAeDatastore.reset
end
unless ENV['CI']
# File store for --only-failures option
config.example_status_persistence_file_path = Rails.root.join('tmp', 'rspec_example_store.txt')
end
if config.backtrace_exclusion_patterns.delete(%r{/lib\d*/ruby/})
config.backtrace_exclusion_patterns << %r{/lib\d*/ruby/[0-9]}
end
config.backtrace_exclusion_patterns << %r{/spec/spec_helper}
config.backtrace_exclusion_patterns << %r{/spec/support/evm_spec_helper}
end
module AutomateClassDefinitionHook
mattr_accessor :hooking
def self.hooked
@hooked ||= []
end
def inherited(other)
AutomateClassDefinitionHook.hook(other)
super
end
def self.require_with_hook(file_name)
self.hooking = true
require(file_name).tap { unhook }
end
class TestLoadStub
def main
end
end
def self.hook(klass)
return unless hooking
if klass.name&.start_with?("ManageIQ::Automate::")
hooked << klass
klass.define_singleton_method(:new) { |*_args| AutomateClassDefinitionHook::TestLoadStub.new }
end
end
def self.unhook
hooked.delete_if { |klass| klass.singleton_class.send(:remove_method, :new) }
self.hooking = false
end
end
Object.singleton_class.prepend(AutomateClassDefinitionHook)
| 26.016807 | 100 | 0.710271 |
acb2792bc3789edf98a358cde16ec92fd72c63d9 | 1,680 | describe command("/bin/hab sup -h") do
its(:stdout) { should match(/The Habitat Supervisor/) }
end
svc_manager = if command("systemctl --help").exit_status == 0
"systemd"
elsif command("initctl --help").exit_status == 0
"upstart"
else
"sysv"
end
describe send("#{svc_manager}_service", "hab-sup") do
it { should be_running }
end
cmd = case svc_manager
when "systemd"
"systemctl restart hab-sup"
when "upstart"
"initctl restart hab-sup"
when "sysv"
"/etc/init.d/hab-sup restart"
end
describe command(cmd) do
its(:exit_status) { should eq(0) }
end
describe send("#{svc_manager}_service", "hab-sup") do
it { should be_running }
end
# Validate HAB_AUTH_TOKEN
case svc_manager
when "systemd"
describe file("/etc/systemd/system/hab-sup.service") do
its("content") { should_not match("Environment = HAB_AUTH_TOKEN=test") }
its("content") { should_not match("Environment = HAB_SUP_GATEWAY_AUTH_TOKEN=secret") }
its("content") { should_not match("LimitNOFILE = 65536") }
end
when "upstart"
describe file("/etc/init/hab-sup.conf") do
its("content") { should_not match("env HAB_AUTH_TOKEN=test") }
its("content") { should_not match("env HAB_SUP_GATEWAY_AUTH_TOKEN=secret") }
end
when "sysv"
describe file("/etc/init.d/hab-sup") do
its("content") { should_not match("export HAB_AUTH_TOKEN=test") }
its("content") { should_not match("export HAB_SUP_GATEWAY_AUTH_TOKEN=secret") }
end
end
describe port(7999) do
it { should be_listening }
end
describe port(7998) do
it { should be_listening }
end
| 27.540984 | 90 | 0.654167 |
1d60e8eb8a79888acae7ea209cd6a827264ed067 | 8,772 | # frozen_string_literal: true
require 'lograge/log_subscribers/action_controller'
require 'active_support/notifications'
require 'active_support/core_ext/string'
require 'logger'
require 'active_record'
require 'rails'
describe Lograge::LogSubscribers::ActionCable do
let(:log_output) { JSON.parse(io_target.string, symbolize_names: true) }
let(:io_target) { StringIO.new }
let(:logger) do
Logger.new(io_target).tap { |logger| logger.formatter = ->(_, _, _, msg) { msg } }
end
let(:subscriber) { Lograge::LogSubscribers::ActionCable.new }
let(:event_params) { { 'foo' => 'bar' } }
let(:event) do
ActiveSupport::Notifications::Event.new(
'perform_action.action_cable',
Time.new(2021, 12, 9, 12, 35, 58, '+00:00'),
Time.new(2021, 12, 9, 12, 35, 59, '+00:00'),
2,
channel_class: 'ActionCableChannel',
data: event_params,
action: 'pong'
)
end
before do
Lograge.logger = logger
Lograge.formatter = Lograge::Formatters::Json.new
end
context 'with custom_options configured for cee output' do
it 'combines the hash properly for the output' do
Lograge.custom_options = { data: 'value' }
subscriber.perform_action(event)
expect(log_output[:data]).to eq('value')
end
it 'combines the output of a lambda properly' do
Lograge.custom_options = ->(_event) { { data: 'value' } }
subscriber.perform_action(event)
expect(log_output[:data]).to eq('value')
end
it 'works when the method returns nil' do
Lograge.custom_options = ->(_event) {}
subscriber.perform_action(event)
expect(log_output).to_not be_empty
end
end
context 'when processing an action with lograge output' do
it 'includes the controller' do
subscriber.perform_action(event)
expect(log_output[:controller]).to eq('ActionCableChannel')
end
it 'includes the action' do
subscriber.perform_action(event)
expect(log_output[:action]).to eq('pong')
end
it 'includes the duration' do
subscriber.perform_action(event)
expect(log_output[:duration]).to eq(1_000_000_000)
end
it 'includes the timestamp' do
subscriber.perform_action(event)
expect(log_output[:timestamp]).to match(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/)
end
it 'includes Datadog trace information in the log output' do
subscriber.perform_action(event)
expect(log_output[:dd][:trace_id]).to eq('0')
expect(log_output[:dd][:span_id]).to eq('0')
expect(log_output[:dd].key?(:env)).to eq(true)
expect(log_output[:dd][:service]).to eq('rspec')
expect(log_output[:dd].key?(:version)).to eq(true)
expect(log_output[:ddsource]).to eq(%w[ruby])
end
context 'when an `ActiveRecord::RecordNotFound` is raised' do
let(:exception) do
ActiveRecord::RecordNotFound.new('Record not found').tap do |e|
e.set_backtrace(['some location', 'another location'])
end
end
before do
ActionDispatch::ExceptionWrapper.rescue_responses[exception.class.name] = :not_found
event.payload[:exception_object] = exception
event.payload[:status] = nil
end
it 'adds a 404 status' do
subscriber.perform_action(event)
expect(log_output[:http][:status_code]).to eq(404)
expect(log_output[:error][:kind]).to eq('ActiveRecord::RecordNotFound')
expect(log_output[:error][:message]).to eq('Record not found')
expect(log_output[:error][:stack]).to eq("some location\nanother location")
end
end
it 'returns a default status when no status or exception is found' do
event.payload[:status] = nil
event.payload[:exception_object] = nil
subscriber.perform_action(event)
expect(log_output[:http][:status_code]).to eq(200)
end
it 'does not include a location by default' do
subscriber.perform_action(event)
expect(log_output[:location]).to be_nil
end
end
context 'with custom_options configured for lograge output' do
it 'combines the hash properly for the output' do
Lograge.custom_options = { data: 'value' }
subscriber.perform_action(event)
expect(log_output[:data]).to eq('value')
end
it 'combines the output of a lambda properly' do
Lograge.custom_options = ->(_event) { { data: 'value' } }
subscriber.perform_action(event)
expect(log_output[:data]).to eq('value')
end
it 'works when the method returns nil' do
Lograge.custom_options = ->(_event) {}
subscriber.perform_action(event)
expect(log_output).to_not be_empty
end
end
context 'when event payload includes a "custom_payload"' do
it 'incorporates the payload correctly' do
event.payload[:custom_payload] = { data: 'value' }
subscriber.perform_action(event)
expect(log_output[:data]).to eq('value')
end
it 'works when custom_payload is nil' do
event.payload[:custom_payload] = nil
subscriber.perform_action(event)
expect(log_output).to_not be_empty
end
end
context 'with before_format configured for lograge output' do
before do
Lograge.before_format = nil
end
it 'outputs correctly' do
Lograge.before_format = lambda do |data, payload|
{ status_code: data[:http][:status_code] }.merge(action: payload[:action])
end
subscriber.perform_action(event)
expect(log_output[:action]).to eq('pong')
expect(log_output[:status_code]).to eq(200)
end
it 'works if the method returns nil' do
Lograge.before_format = ->(_data, _payload) {}
subscriber.perform_action(event)
expect(log_output).to_not be_empty
end
end
context 'with ignore configured' do
before do
Lograge.ignore_nothing
end
it 'does not log ignored controller actions given a single ignored action' do
Lograge.ignore_actions 'ActionCableChannel#pong'
subscriber.perform_action(event)
expect(io_target.string).to be_blank
end
it 'does not log ignored controller actions given a single ignored action after a custom ignore' do
Lograge.ignore(->(_event) { false })
Lograge.ignore_actions 'ActionCableChannel#pong'
subscriber.perform_action(event)
expect(io_target.string).to be_blank
end
it 'logs non-ignored controller actions given a single ignored action' do
Lograge.ignore_actions 'ActionCableChannel#bar'
subscriber.perform_action(event)
expect(io_target.string).to be_present
end
it 'does not log ignored controller actions given multiple ignored actions' do
Lograge.ignore_actions ['ActionCableChannel#bar', 'ActionCableChannel#pong', 'OtherChannel#foo']
subscriber.perform_action(event)
expect(io_target.string).to be_blank
end
it 'logs non-ignored controller actions given multiple ignored actions' do
Lograge.ignore_actions ['ActionCableChannel#bar', 'OtherChannel#foo']
subscriber.perform_action(event)
expect(log_output).to_not be_empty
end
it 'does not log ignored events' do
Lograge.ignore(->(event) { event.payload[:action] == 'pong' })
subscriber.perform_action(event)
expect(io_target.string).to be_blank
end
it 'logs non-ignored events' do
Lograge.ignore(->(event) { event.payload[:action] == 'foo' })
subscriber.perform_action(event)
expect(log_output).not_to be_empty
end
it 'does not choke on nil ignore_actions input' do
Lograge.ignore_actions nil
subscriber.perform_action(event)
expect(log_output).not_to be_empty
end
it 'does not choke on nil ignore input' do
Lograge.ignore nil
subscriber.perform_action(event)
expect(log_output).not_to be_empty
end
end
describe 'other actions' do
%i[subscribe unsubscribe connect disconnect].each do |action_name|
let(:event) do
ActiveSupport::Notifications::Event.new(
"#{action_name}.action_cable",
Time.new(2021, 12, 9, 12, 35, 58, '+00:00'),
Time.new(2021, 12, 9, 12, 35, 59, '+00:00'),
2,
channel_class: 'ActionCableChannel',
data: event_params,
action: 'pong'
)
end
it 'generates output' do
subscriber.perform_action(event)
expect(log_output[:controller]).to eq('ActionCableChannel')
expect(log_output[:action]).to eq('pong')
end
end
end
it "will fallback to ActiveSupport's logger if one isn't configured" do
Lograge.logger = nil
ActiveSupport::LogSubscriber.logger = logger
subscriber.perform_action(event)
expect(log_output).to_not be_empty
end
end
| 31.328571 | 103 | 0.672367 |
e224775b81b70bf77f74170adffb6e854f1f418b | 10,148 | #!/usr/bin/env ruby
# Copyright 2013-2014 Bazaarvoice, 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.
require "bundler/setup"
require "cloudformation-ruby-dsl/cfntemplate"
require "cloudformation-ruby-dsl/table"
# Note: this is only intended to demonstrate the cloudformation-ruby-dsl. It compiles
# and validates correctly, but won't produce a viable CloudFormation stack.
template do
# Metadata may be embedded into the stack, as per http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/metadata-section-structure.html
# The below definition produces CloudFormation interface metadata.
metadata "AWS::CloudFormation::Interface", {
ParameterGroups: [
{
Label: { default: "Instance options" },
Parameters: %w[InstanceType ImageId KeyPairName]
},
{
Label: { default: "Other options" },
Parameters: %w[Label EmailAddress]
}
],
ParameterLabels: {
EmailAddress: {
default: "We value your privacy!"
}
}
}
parameter "Label",
Description: "The label to apply to the servers.",
Type: "String",
MinLength: "2",
MaxLength: "25",
AllowedPattern: "[_a-zA-Z0-9]*",
ConstraintDescription: "Maximum length of the Label parameter may not exceed 25 characters and may only contain letters, numbers and underscores.",
# The :Immutable attribute is a Ruby CFN extension. It affects the behavior of the '<template> update ...'
# operation in that a stack update may not change the values of parameters marked w/:Immutable => true.
Immutable: true
parameter "InstanceType",
Description: "EC2 instance type",
Type: "String",
Default: "m2.xlarge",
AllowedValues: %w[t1.micro m1.small m1.medium m1.large m1.xlarge m2.xlarge m2.2xlarge m2.4xlarge c1.medium c1.xlarge],
ConstraintDescription: "Must be a valid EC2 instance type."
parameter "ImageId",
Description: "EC2 Image ID",
Type: "String",
Default: "ami-255bbc4c",
AllowedPattern: "ami-[a-f0-9]{8}",
ConstraintDescription: "Must be ami-XXXXXXXX (where X is a hexadecimal digit)"
parameter "KeyPairName",
Description: "Name of KeyPair to use.",
Type: "String",
MinLength: "1",
MaxLength: "40",
Default: parameters["Label"]
parameter "EmailAddress",
Type: "String",
Description: "Email address at which to send notification events."
parameter "BucketName",
Type: "String",
Description: "Name of the bucket to upload to."
mapping "InlineExampleMap",
team1: {
name: "test1",
email: "[email protected]"
},
team2: {
name: "test2",
email: "[email protected]"
}
# Generates mappings from external files with various formats.
mapping "JsonExampleMap", "maps/map.json"
mapping "RubyExampleMap", "maps/map.rb"
mapping "YamlExampleMap", "maps/map.yaml"
# Loads JSON mappings dynamically from example directory.
Dir.entries("maps/more_maps").each_with_index do |path, index|
next if (path == ".") || (path == "..")
mapping "ExampleMap#{index - 1}", "maps/more_maps/#{path}"
end
# Selects all rows in the table which match the name/value pairs of the predicate object and returns a
# set of nested maps, where the key for the map at level n is the key at index n in the specified keys,
# except for the last key in the specified keys which is used to determine the value of the leaf-level map.
text = Table.load "maps/table.txt"
mapping "TableExampleMap",
text.get_map({ column0: "foo" }, :column1, :column2, :column3)
# Shows how to create a table useful for looking up subnets that correspond to a particular env/region for eg. vpc placement.
vpc = Table.load "maps/vpc.txt"
mapping "TableExampleMultimap",
vpc.get_multimap({ visibility: "private", zone: %w[a c] }, :env, :region, :subnet)
# Shows how to use a table for iterative processing.
domains = Table.load "maps/domains.txt"
domains.get_multihash(:purpose, { product: "demo", alias: "true" }, :prefix, :target, :alias_hosted_zone_id).each_pair do |key, value|
resource key + "Route53RecordSet", Type: "AWS::Route53::RecordSet", Properties: {
Comment: "",
HostedZoneName: "bazaarvoice.com",
Name: value[:prefix] + ".bazaarvoice.com",
Type: "A",
AliasTarget: {
DNSName: value[:target],
HostedZoneId: value[:alias_hosted_zone_id]
}
}
end
# The tag type is a DSL extension; it is not a property of actual CloudFormation templates.
# These tags are excised from the template and used to generate a series of --tag arguments
# which are passed to CloudFormation when a stack is created.
# They do not ultimately appear in the expanded CloudFormation template.
# The diff subcommand will compare tags with the running stack and identify any changes,
# but a stack update will do the diff and throw an error on any immutable tags update attempt.
# The tags are propagated to all resources created by the stack, including the stack itself.
# If a resource has its own tag with the same name as CF's it's not overwritten.
#
# Amazon has set the following restrictions on CloudFormation tags:
# => limit 10
# CloudFormation tags declaration examples:
tag "My:New:Tag",
Value: "ImmutableTagValue",
Immutable: true
tag :MyOtherTag,
Value: "My Value With Spaces"
tag(:"tag:name", Value: "tag_value", Immutable: true)
# Following format is deprecated and not advised. Please declare CloudFormation tags as described above.
tag TagName: "tag_value" # It's immutable.
resource "SecurityGroup", Type: "AWS::EC2::SecurityGroup", Properties: {
GroupDescription: "Lets any vpc traffic in.",
SecurityGroupIngress: { IpProtocol: "-1", FromPort: "0", ToPort: "65535", CidrIp: "10.0.0.0/8" }
}
resource "ASG", Type: "AWS::AutoScaling::AutoScalingGroup", Properties: {
AvailabilityZones: "us-east-1",
HealthCheckType: "EC2",
LaunchConfigurationName: ref("LaunchConfig"),
MinSize: 1,
MaxSize: 5,
NotificationConfiguration: {
TopicARN: ref("EmailSNSTopic"),
NotificationTypes: %w[autoscaling:EC2_INSTANCE_LAUNCH autoscaling:EC2_INSTANCE_LAUNCH_ERROR autoscaling:EC2_INSTANCE_TERMINATE autoscaling:EC2_INSTANCE_TERMINATE_ERROR]
},
Tags: [
{
Key: "Name",
# Grabs a value in an external map file.
Value: find_in_map("TableExampleMap", "corge", "grault"),
PropagateAtLaunch: "true"
},
{
Key: "Label",
Value: parameters["Label"],
PropagateAtLaunch: "true"
}
]
}
resource "EmailSNSTopic", Type: "AWS::SNS::Topic", Properties: {
Subscription: [
{
Endpoint: ref("EmailAddress"),
Protocol: "email"
}
]
}
resource "WaitConditionHandle", Type: "AWS::CloudFormation::WaitConditionHandle", Properties: {}
resource "WaitCondition", Type: "AWS::CloudFormation::WaitCondition", DependsOn: "ASG", Properties: {
Handle: ref("WaitConditionHandle"),
Timeout: 1200,
Count: "1"
}
resource "LaunchConfig", Type: "AWS::AutoScaling::LaunchConfiguration", Properties: {
ImageId: parameters["ImageId"],
KeyName: ref("KeyPairName"),
IamInstanceProfile: ref("InstanceProfile"),
InstanceType: ref("InstanceType"),
InstanceMonitoring: "false",
SecurityGroups: [ref("SecurityGroup")],
BlockDeviceMappings: [
{ DeviceName: "/dev/sdb", VirtualName: "ephemeral0" },
{ DeviceName: "/dev/sdc", VirtualName: "ephemeral1" },
{ DeviceName: "/dev/sdd", VirtualName: "ephemeral2" },
{ DeviceName: "/dev/sde", VirtualName: "ephemeral3" }
],
# Loads an external userdata script with an interpolated argument.
UserData: base64(interpolate(file("userdata.sh"), time: Time.now))
}
resource "InstanceProfile", Type: "AWS::IAM::InstanceProfile", Properties: {
# use cfn intrinsic conditional to choose the 2nd value because the expression evaluates to false
Path: fn_if(equal(3, 0), "/unselected/", "/"),
Roles: [ref("InstanceRole")]
}
resource "InstanceRole", Type: "AWS::IAM::Role", Properties: {
AssumeRolePolicyDocument: {
Statement: [
{
Effect: "Allow",
Principal: { Service: ["ec2.amazonaws.com"] },
Action: ["sts:AssumeRole"]
}
]
},
Path: "/"
}
# Use sub to set bucket names for an S3 Policy.
resource "ManagedPolicy", Type: "AWS::IAM::ManagedPolicy", Properties: {
Description: "Access policy for S3 Buckets",
PolicyDocument: {
Version: "2012-10-17",
Statement: [
{
Action: ["s3:ListBucket"],
Effect: "Allow",
Resource: [
sub("arn:aws:s3:::${BucketName}"),
sub("arn:aws:s3:::${BaseName}${Hash}", { BaseName: "Bucket", Hash: "3bsd73w" })
]
}
]
}
}
# add conditions that can be used elsewhere in the template
condition "myCondition", fn_and(equal("one", "two"), not_equal("three", "four"))
output "EmailSNSTopicARN",
Value: ref("EmailSNSTopic"),
Description: "ARN of SNS Topic used to send emails on events."
output "MappingLookup",
Value: find_in_map("TableExampleMap", "corge", "grault"),
Description: "An example map lookup."
end.exec!
| 37.172161 | 174 | 0.650572 |
33fd82e8f026ad6fcc012bd3fe05a8c4a5b1797e | 1,207 | module Boxcutter
class Server
def self.all
api = Api.new(*ENV['BBG_API_KEY'].split(':'))
resp = api.servers
if resp.success?
resp.parsed.map {|attrs| new(api, attrs)}
else
[]
end
end
def self.find_by_hostname(hostname)
all.detect {|server| server.hostname == hostname}
end
attr_reader :api
def initialize(api, attrs)
@api = api
@attrs = attrs
end
def to_s
"#<Server id:'#{id}' hostname:'#{hostname}' description:'#{description}' status:'#{status}'>"
end
def ips
@attrs["ips"].map {|ip| ip["address"]}
end
def memory
@attrs["memory"]
end
def id
@attrs["id"]
end
def storage
@attrs["storage"]
end
def location_id
@attrs["location_id"]
end
def hostname
@attrs["hostname"]
end
def description
@attrs["description"]
end
def cpu
@attrs["cpu"]
end
def status
@attrs["status"]
end
def lb_applications
@attrs["lb_applications"].map do |lb_app_attrs|
LoadBalancer::Application.find(lb_app_attrs["lb_application_id"], api)
end
end
end
end
| 16.763889 | 99 | 0.561723 |
87a4b703b1fa8cc0703a39aa678dae667716c34e | 270 | # encoding: UTF-8
require File.join(File.dirname(__FILE__), "spec_helper")
describe Escodegen do
describe "#load_path" do
it "escodegen.js should exist at the load path" do
File.should exist(File.join(Escodegen.load_path, "escodegen.js"))
end
end
end | 24.545455 | 71 | 0.722222 |
3873a1d0b786c025e4ad9fa0e68812153c078080 | 470 | require 'bundler'
Bundler.require()
def fake_song(title, release_year, artist)
{:title => title.to_s, :release_year => release_year.to_s, :artist => artist.to_s}
end
get '/api/shake_it_cough' do
cross_origin
fake_song('shake_it_cough','1987','Baylor_Diff')
end
get '/api/strip_pop_lupe' do
cross_origin
fake_song('strip_pop_lupe','2112','Nice_by_Nurture')
end
get '/api/theme_to_love' do
cross_origin
fake_song('cross_origin','2008','theoDaGreat')
end
| 21.363636 | 84 | 0.744681 |
e8e0cbecfb7f2feb8dca9adf7858b8dc2f755795 | 452 | class CreateBoringScienceArticles < ActiveRecord::Migration[5.0]
def change
create_table :boring_science_articles do |t|
t.string :blog, null: false, index: true
t.string :title, null: false
t.string :summary
t.text :body, null: false
t.date :publication_date
t.string :slug, null: false, index: { unique: true }
t.references :author, polymorphic: true, index: true
t.timestamps
end
end
end
| 28.25 | 64 | 0.665929 |
286a6c3de97814423b4e2b1be23a9800688500a9 | 2,232 | RSpec.shared_examples Hcheck::ApplicationHelpers::Responders do
require 'pg'
require 'rack/test'
include Rack::Test::Methods
def app
application
end
before do
ENV['HCHECK_SECURE'] = nil
end
after(:all) do
ENV['HCHECK_SECURE'] = 'true'
end
context 'all checks pass' do
it 'displays Ok status page with 2xx status code' do
allow(PG::Connection).to receive(:new) { double(:connection, close: true) }
get path
expect(last_response.body).to include('Hcheck Status Page')
expect(last_response.body).to include('Core Store')
expect(last_response.body).to include('Ok')
expect(last_response.status).to eql 200
end
end
context 'secure path' do
context 'secured path is activated but token is not setup' do
it 'displays config error with 4xx response' do
ENV['HCHECK_SECURE'] = 'true'
get path
expect(last_response.body).to include(Hcheck::Errors::IncompleteAuthSetup::MSG)
expect(last_response.status).to eql 401
end
end
context 'secured path is activated with token' do
before do
ENV['HCHECK_SECURE'] = 'true'
ENV['HCHECK_ACCESS_TOKEN'] = 'blah'
allow(PG::Connection).to receive(:new) { double(:connection, close: true) }
end
after(:all) do
ENV['HCHECK_ACCESS_TOKEN'] = nil
end
context 'token is valid' do
it 'displays status page with 2xx response' do
get "#{path}?token=blah"
expect(last_response.body).to include('Hcheck Status Page')
expect(last_response.status).to eql 200
end
end
context 'token is not present' do
it 'displays auth error with 4xx response' do
get path
expect(last_response.body).to include(Hcheck::Errors::InvalidAuthentication::MSG)
expect(last_response.status).to eql 401
end
end
context 'token is not valid' do
it 'displays auth error with 4xx response' do
get "#{path}?token=xxx"
expect(last_response.body).to include(Hcheck::Errors::InvalidAuthentication::MSG)
expect(last_response.status).to eql 401
end
end
end
end
end
| 26.258824 | 91 | 0.638889 |
21d707947795c90e0736a7c519ffcbf1ae1ad655 | 1,455 | class PagesController < ApplicationController
before_action :authenticate_user!, only: [:admin_panel]
def index
@user = User.new
end
def ticket
@ticket = Ticket.where(user_id: current_user.id).first
if Ticket.where(tour: "1").count >= 100
@disable_radio_button_tour_1 = true
else
@disable_radio_button_tour_1 = false
end
if Ticket.where(tour: "2").count >= 100
@disable_radio_button_tour_2 = true
else
@disable_radio_button_tour_2 = false
end
if Ticket.where(tour: "3").count >= 100
@disable_radio_button_tour_3 = true
else
@disable_radio_button_tour_3 = false
end
end
def admin_panel
if current_user.admin == false
redirect_to "/unauthorised_admin_panel_entry"
end
if params.fetch("ticket_code", nil) != nil
@ticket = Ticket.where(code: params.fetch("ticket_code", nil)).first
end
end
def unauthorised_admin_panel_entry
end
def ticket_checking_form
redirect_to controller: 'pages', action: 'admin_panel', ticket_code: params.dig("code", "ticket_code")
end
def tour_selection_form
ticket = current_user.ticket
ticket.tour = params["ticket_tour_change"]["tour"]
ticket.save
redirect_to controller: "pages", action: "ticket"
end
end
| 27.980769 | 110 | 0.617182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.