repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/railtie.rb | lib/simple_form/railtie.rb | # frozen_string_literal: true
require 'rails/railtie'
module SimpleForm
class Railtie < Rails::Railtie
config.eager_load_namespaces << SimpleForm
config.after_initialize do
unless SimpleForm.configured?
warn '[Simple Form] Simple Form is not configured in the application and will use the default values.' +
' Use `rails generate simple_form:install` to generate the Simple Form configuration.'
end
end
initializer "simple_form.deprecator" do |app|
app.deprecators[:simple_form] = SimpleForm.deprecator if app.respond_to?(:deprecators)
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/form_builder.rb | lib/simple_form/form_builder.rb | # frozen_string_literal: true
require 'active_support/core_ext/object/deep_dup'
require 'simple_form/map_type'
require 'simple_form/tags'
module SimpleForm
class FormBuilder < ActionView::Helpers::FormBuilder
attr_reader :template, :object_name, :object, :wrapper
# When action is create or update, we still should use new and edit
ACTIONS = {
'create' => 'new',
'update' => 'edit'
}
ATTRIBUTE_COMPONENTS = %i[html5 min_max maxlength minlength placeholder pattern readonly]
extend MapType
include SimpleForm::Inputs
map_type :text, :hstore, :json, :jsonb, to: SimpleForm::Inputs::TextInput
map_type :file, to: SimpleForm::Inputs::FileInput
map_type :string, :email, :search, :tel, :url, :uuid, :citext, to: SimpleForm::Inputs::StringInput
map_type :password, to: SimpleForm::Inputs::PasswordInput
map_type :integer, :decimal, :float, to: SimpleForm::Inputs::NumericInput
map_type :range, to: SimpleForm::Inputs::RangeInput
map_type :check_boxes, to: SimpleForm::Inputs::CollectionCheckBoxesInput
map_type :radio_buttons, to: SimpleForm::Inputs::CollectionRadioButtonsInput
map_type :rich_text_area, to: SimpleForm::Inputs::RichTextAreaInput
map_type :select, to: SimpleForm::Inputs::CollectionSelectInput
map_type :grouped_select, to: SimpleForm::Inputs::GroupedCollectionSelectInput
map_type :date, :time, :datetime, to: SimpleForm::Inputs::DateTimeInput
map_type :country, :time_zone, to: SimpleForm::Inputs::PriorityInput
map_type :boolean, to: SimpleForm::Inputs::BooleanInput
map_type :hidden, to: SimpleForm::Inputs::HiddenInput
def self.discovery_cache
@discovery_cache ||= {}
end
def initialize(*) #:nodoc:
super
@object = convert_to_model(@object)
@defaults = options[:defaults]
@wrapper = SimpleForm.wrapper(options[:wrapper] || SimpleForm.default_wrapper)
end
# Basic input helper, combines all components in the stack to generate
# input html based on options the user define and some guesses through
# database column information. By default a call to input will generate
# label + input + hint (when defined) + errors (when exists), and all can
# be configured inside a wrapper html.
#
# If a block is given, the contents of the block will replace the input
# field that would otherwise be generated automatically. The content will
# be given a label and wrapper div to make it consistent with the other
# elements in the form.
#
# == Examples
#
# # Imagine @user has error "can't be blank" on name
# simple_form_for @user do |f|
# f.input :name, hint: 'My hint'
# end
#
# This is the output html (only the input portion, not the form):
#
# <label class="string required" for="user_name">
# <abbr title="required">*</abbr> Super User Name!
# </label>
# <input class="string required" id="user_name" maxlength="100"
# name="user[name]" type="text" value="Carlos" />
# <span class="hint">My hint</span>
# <span class="error">can't be blank</span>
#
# Each database type will render a default input, based on some mappings and
# heuristic to determine which is the best option.
#
# You have some options for the input to enable/disable some functions:
#
# as: allows you to define the input type you want, for instance you
# can use it to generate a text field for a date column.
#
# required: defines whether this attribute is required or not. True
# by default.
#
# The fact SimpleForm is built in components allow the interface to be unified.
# So, for instance, if you need to disable :hint for a given input, you can pass
# hint: false. The same works for :error, :label and :wrapper.
#
# Besides the html for any component can be changed. So, if you want to change
# the label html you just need to give a hash to :label_html. To configure the
# input html, supply :input_html instead and so on.
#
# == Options
#
# Some inputs, as datetime, time and select allow you to give extra options, like
# prompt and/or include blank. Such options are given in plainly:
#
# f.input :created_at, include_blank: true
#
# == Collection
#
# When playing with collections (:radio_buttons, :check_boxes and :select
# inputs), you have three extra options:
#
# collection: use to determine the collection to generate the radio or select
#
# label_method: the method to apply on the array collection to get the label
#
# value_method: the method to apply on the array collection to get the value
#
# == Priority
#
# Some inputs, as :time_zone and :country accepts a :priority option. If none is
# given SimpleForm.time_zone_priority and SimpleForm.country_priority are used respectively.
#
def input(attribute_name, options = {}, &block)
options = @defaults.deep_dup.deep_merge(options) if @defaults
input = find_input(attribute_name, options, &block)
wrapper = find_wrapper(input.input_type, options)
wrapper.render input
end
alias :attribute :input
# Creates a input tag for the given attribute. All the given options
# are sent as :input_html.
#
# == Examples
#
# simple_form_for @user do |f|
# f.input_field :name
# end
#
# This is the output html (only the input portion, not the form):
#
# <input class="string required" id="user_name" maxlength="100"
# name="user[name]" type="text" value="Carlos" />
#
# It also support validation classes once it is configured.
#
# # config/initializers/simple_form.rb
# SimpleForm.setup do |config|
# config.input_field_valid_class = 'is-valid'
# config.input_field_error_class = 'is-invalid'
# end
#
# simple_form_for @user do |f|
# f.input_field :name
# end
#
# When the validation happens, the input will be rendered with
# the class configured according to the validation:
#
# - when the input is valid:
#
# <input class="is-valid string required" id="user_name" value="Carlos" />
#
# - when the input is invalid:
#
# <input class="is-invalid string required" id="user_name" value="" />
#
def input_field(attribute_name, options = {})
components = (wrapper.components.map(&:namespace) & ATTRIBUTE_COMPONENTS)
options = options.dup
options[:input_html] = options.except(:as, :boolean_style, :collection, :disabled, :label_method, :value_method, :prompt, *components)
options = @defaults.deep_dup.deep_merge(options) if @defaults
input = find_input(attribute_name, options)
wrapper = find_wrapper(input.input_type, options)
components = build_input_field_components(components.push(:input))
SimpleForm::Wrappers::Root.new(components, wrapper.options.merge(wrapper: false)).render input
end
# Helper for dealing with association selects/radios, generating the
# collection automatically. It's just a wrapper to input, so all options
# supported in input are also supported by association. Some extra options
# can also be given:
#
# == Examples
#
# simple_form_for @user do |f|
# f.association :company # Company.all
# end
#
# f.association :company, collection: Company.all(order: 'name')
# # Same as using :order option, but overriding collection
#
# == Block
#
# When a block is given, association simple behaves as a proxy to
# simple_fields_for:
#
# f.association :company do |c|
# c.input :name
# c.input :type
# end
#
# From the options above, only :collection can also be supplied.
#
# Please note that the association helper is currently only tested with Active Record. Depending on the ORM you are using your mileage may vary.
#
def association(association, options = {}, &block)
options = options.dup
return simple_fields_for(*[association,
options.delete(:collection), options].compact, &block) if block_given?
raise ArgumentError, "Association cannot be used in forms not associated with an object" unless @object
reflection = find_association_reflection(association)
raise "Association #{association.inspect} not found" unless reflection
options[:as] ||= :select
options[:collection] ||= fetch_association_collection(reflection, options)
attribute = build_association_attribute(reflection, association, options)
input(attribute, options.merge(reflection: reflection))
end
# Creates a button:
#
# form_for @user do |f|
# f.button :submit
# end
#
# It just acts as a proxy to method name given. We also alias original Rails
# button implementation (3.2 forward (to delegate to the original when
# calling `f.button :button`.
#
alias_method :button_button, :button
def button(type, *args, &block)
options = args.extract_options!.dup
options[:class] = [SimpleForm.button_class, options[:class]].compact
args << options
if respond_to?(:"#{type}_button")
send(:"#{type}_button", *args, &block)
else
send(type, *args, &block)
end
end
# Creates an error tag based on the given attribute, only when the attribute
# contains errors. All the given options are sent as :error_html.
#
# == Examples
#
# f.error :name
# f.error :name, id: "cool_error"
#
def error(attribute_name, options = {})
options = options.dup
options[:error_html] = options.except(:error_tag, :error_prefix, :error_method)
column = find_attribute_column(attribute_name)
input_type = default_input_type(attribute_name, column, options)
wrapper.find(:error).
render(SimpleForm::Inputs::Base.new(self, attribute_name, column, input_type, options))
end
# Return the error but also considering its name. This is used
# when errors for a hidden field need to be shown.
#
# == Examples
#
# f.full_error :token #=> <span class="error">Token is invalid</span>
#
def full_error(attribute_name, options = {})
options = options.dup
options[:error_prefix] ||= if object.class.respond_to?(:human_attribute_name)
object.class.human_attribute_name(attribute_name.to_s, { base: object })
else
attribute_name.to_s.humanize
end
error(attribute_name, options)
end
# Creates a hint tag for the given attribute. Accepts a symbol indicating
# an attribute for I18n lookup or a string. All the given options are sent
# as :hint_html.
#
# == Examples
#
# f.hint :name # Do I18n lookup
# f.hint :name, id: "cool_hint"
# f.hint "Don't forget to accept this"
#
def hint(attribute_name, options = {})
options = options.dup
options[:hint_html] = options.except(:hint_tag, :hint)
if attribute_name.is_a?(String)
options[:hint] = attribute_name
attribute_name, column, input_type = nil, nil, nil
else
column = find_attribute_column(attribute_name)
input_type = default_input_type(attribute_name, column, options)
end
wrapper.find(:hint).
render(SimpleForm::Inputs::Base.new(self, attribute_name, column, input_type, options))
end
# Creates a default label tag for the given attribute. You can give a label
# through the :label option or using i18n. All the given options are sent
# as :label_html.
#
# == Examples
#
# f.label :name # Do I18n lookup
# f.label :name, "Name" # Same behavior as Rails, do not add required tag
# f.label :name, label: "Name" # Same as above, but adds required tag
#
# f.label :name, required: false
# f.label :name, id: "cool_label"
#
def label(attribute_name, *args)
return super if args.first.is_a?(String) || block_given?
options = args.extract_options!.dup
options[:label_html] = options.except(:label, :label_text, :required, :as)
column = find_attribute_column(attribute_name)
input_type = default_input_type(attribute_name, column, options)
SimpleForm::Inputs::Base.new(self, attribute_name, column, input_type, options).label
end
# Creates an error notification message that only appears when the form object
# has some error. You can give a specific message with the :message option,
# otherwise it will look for a message using I18n. All other options given are
# passed straight as html options to the html tag.
#
# == Examples
#
# f.error_notification
# f.error_notification message: 'Something went wrong'
# f.error_notification id: 'user_error_message', class: 'form_error'
#
def error_notification(options = {})
SimpleForm::ErrorNotification.new(self, options).render
end
# Create a collection of radio inputs for the attribute. Basically this
# helper will create a radio input associated with a label for each
# text/value option in the collection, using value_method and text_method
# to convert these text/value. You can give a symbol or a proc to both
# value_method and text_method, that will be evaluated for each item in
# the collection.
#
# == Examples
#
# form_for @user do |f|
# f.collection_radio_buttons :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
# end
#
# <input id="user_options_true" name="user[options]" type="radio" value="true" />
# <label class="collection_radio_buttons" for="user_options_true">Yes</label>
# <input id="user_options_false" name="user[options]" type="radio" value="false" />
# <label class="collection_radio_buttons" for="user_options_false">No</label>
#
# It is also possible to give a block that should generate the radio +
# label. To wrap the radio with the label, for instance:
#
# form_for @user do |f|
# f.collection_radio_buttons(
# :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
# ) do |b|
# b.label { b.radio_button + b.text }
# end
# end
#
# == Options
#
# Collection radio accepts some extra options:
#
# * checked => the value that should be checked initially.
#
# * disabled => the value or values that should be disabled. Accepts a single
# item or an array of items.
#
# * collection_wrapper_tag => the tag to wrap the entire collection.
#
# * collection_wrapper_class => the CSS class to use for collection_wrapper_tag
#
# * item_wrapper_tag => the tag to wrap each item in the collection.
#
# * item_wrapper_class => the CSS class to use for item_wrapper_tag
#
# * a block => to generate the label + radio or any other component.
def collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
SimpleForm::Tags::CollectionRadioButtons.new(@object_name, method, @template, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options)).render(&block)
end
# Creates a collection of check boxes for each item in the collection,
# associated with a clickable label. Use value_method and text_method to
# convert items in the collection for use as text/value in check boxes.
# You can give a symbol or a proc to both value_method and text_method,
# that will be evaluated for each item in the collection.
#
# == Examples
#
# form_for @user do |f|
# f.collection_check_boxes :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
# end
#
# <input name="user[options][]" type="hidden" value="" />
# <input id="user_options_true" name="user[options][]" type="checkbox" value="true" />
# <label class="collection_check_boxes" for="user_options_true">Yes</label>
# <input name="user[options][]" type="hidden" value="" />
# <input id="user_options_false" name="user[options][]" type="checkbox" value="false" />
# <label class="collection_check_boxes" for="user_options_false">No</label>
#
# It is also possible to give a block that should generate the check box +
# label. To wrap the check box with the label, for instance:
#
# form_for @user do |f|
# f.collection_check_boxes(
# :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
# ) do |b|
# b.label { b.check_box + b.text }
# end
# end
#
# == Options
#
# Collection check box accepts some extra options:
#
# * checked => the value or values that should be checked initially. Accepts
# a single item or an array of items. It overrides existing associations.
#
# * disabled => the value or values that should be disabled. Accepts a single
# item or an array of items.
#
# * collection_wrapper_tag => the tag to wrap the entire collection.
#
# * collection_wrapper_class => the CSS class to use for collection_wrapper_tag. This option
# is ignored if the :collection_wrapper_tag option is blank.
#
# * item_wrapper_tag => the tag to wrap each item in the collection.
#
# * item_wrapper_class => the CSS class to use for item_wrapper_tag
#
# * a block => to generate the label + check box or any other component.
def collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
SimpleForm::Tags::CollectionCheckBoxes.new(@object_name, method, @template, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options)).render(&block)
end
# Extract the model names from the object_name mess, ignoring numeric and
# explicit child indexes.
#
# Example:
#
# route[blocks_attributes][0][blocks_learning_object_attributes][1][foo_attributes]
# ["route", "blocks", "blocks_learning_object", "foo"]
#
def lookup_model_names #:nodoc:
@lookup_model_names ||= begin
child_index = options[:child_index]
names = object_name.to_s.scan(/(?!\d)\w+/).flatten
names.delete(child_index) if child_index
names.each { |name| name.gsub!('_attributes', '') }
names.freeze
end
end
# The action to be used in lookup.
def lookup_action #:nodoc:
@lookup_action ||= begin
action = template.controller && template.controller.action_name
return unless action
action = action.to_s
ACTIONS[action] || action
end
end
private
def fetch_association_collection(reflection, options)
options.fetch(:collection) do
relation = reflection.klass.all
if reflection.respond_to?(:scope) && reflection.scope
if reflection.scope.parameters.any?
relation = reflection.klass.instance_exec(object, &reflection.scope)
else
relation = reflection.klass.instance_exec(&reflection.scope)
end
else
order = reflection.options[:order]
conditions = reflection.options[:conditions]
conditions = object.instance_exec(&conditions) if conditions.respond_to?(:call)
relation = relation.where(conditions) if relation.respond_to?(:where) && conditions.present?
relation = relation.order(order) if relation.respond_to?(:order)
end
relation
end
end
def build_association_attribute(reflection, association, options)
case reflection.macro
when :belongs_to
(reflection.respond_to?(:options) && reflection.options[:foreign_key]) || :"#{reflection.name}_id"
when :has_one
raise ArgumentError, ":has_one associations are not supported by f.association"
else
if options[:as] == :select || options[:as] == :grouped_select
html_options = options[:input_html] ||= {}
html_options[:multiple] = true unless html_options.key?(:multiple)
end
# Force the association to be preloaded for performance.
if options[:preload] != false && object.respond_to?(association)
target = object.send(association)
target.to_a if target.respond_to?(:to_a)
end
:"#{reflection.name.to_s.singularize}_ids"
end
end
# Find an input based on the attribute name.
def find_input(attribute_name, options = {}, &block)
column = find_attribute_column(attribute_name)
input_type = default_input_type(attribute_name, column, options)
if block_given?
SimpleForm::Inputs::BlockInput.new(self, attribute_name, column, input_type, options, &block)
else
find_mapping(input_type).new(self, attribute_name, column, input_type, options)
end
end
# Attempt to guess the better input type given the defined options. By
# default always fallback to the user :as option, or to a :select when a
# collection is given.
def default_input_type(attribute_name, column, options)
return options[:as].to_sym if options[:as]
custom_type = find_custom_type(attribute_name.to_s) and return custom_type
return :select if options[:collection]
input_type = column.try(:type)
case input_type
when :timestamp
:datetime
when :string, :citext, nil
case attribute_name.to_s
when /(?:\b|\W|_)password(?:\b|\W|_)/ then :password
when /(?:\b|\W|_)time_zone(?:\b|\W|_)/ then :time_zone
when /(?:\b|\W|_)country(?:\b|\W|_)/ then :country
when /(?:\b|\W|_)email(?:\b|\W|_)/ then :email
when /(?:\b|\W|_)phone(?:\b|\W|_)/ then :tel
when /(?:\b|\W|_)url(?:\b|\W|_)/ then :url
else
file_method?(attribute_name) ? :file : (input_type || :string)
end
else
input_type
end
end
def find_custom_type(attribute_name)
SimpleForm.input_mappings.find { |match, type|
attribute_name =~ match
}.try(:last) if SimpleForm.input_mappings
end
# Internal: Try to discover whether an attribute corresponds to a file or not.
#
# Most upload Gems add some kind of attributes to the ActiveRecord's model they are included in.
# This method tries to guess if an attribute belongs to some of these Gems by checking the presence
# of their methods using `#respond_to?`.
#
# Note: This does not support multiple file upload inputs, as this is very application-specific.
#
# The order here was chosen based on the popularity of Gems:
#
# - `#{attribute_name}_attachment` - ActiveStorage >= `5.2` and Refile >= `0.2.0` <= `0.4.0`
# - `remote_#{attribute_name}_url` - Refile >= `0.3.0` and CarrierWave >= `0.2.2`
# - `#{attribute_name}_attacher` - Refile >= `0.4.0` and Shrine >= `0.9.0`
# - `#{attribute_name}_file_name` - Paperclip ~> `2.0` (added for backwards compatibility)
#
# Returns a Boolean.
def file_method?(attribute_name)
@object.respond_to?("#{attribute_name}_attachment") ||
@object.respond_to?("#{attribute_name}_attachments") ||
@object.respond_to?("remote_#{attribute_name}_url") ||
@object.respond_to?("#{attribute_name}_attacher") ||
@object.respond_to?("#{attribute_name}_file_name")
end
def find_attribute_column(attribute_name)
if @object.respond_to?(:type_for_attribute) && @object.has_attribute?(attribute_name)
detected_type = @object.type_for_attribute(attribute_name.to_s)
# Some attributes like ActiveRecord::Encryption::EncryptedAttribute are detected
# as different type, in that case we need to use the original type
detected_type.respond_to?(:cast_type) ? detected_type.cast_type : detected_type
elsif @object.respond_to?(:column_for_attribute) && @object.has_attribute?(attribute_name)
@object.column_for_attribute(attribute_name)
end
end
def find_association_reflection(association)
if @object.class.respond_to?(:reflect_on_association)
@object.class.reflect_on_association(association)
end
end
# Attempts to find a mapping. It follows the following rules:
#
# 1) It tries to find a registered mapping, if succeeds:
# a) Try to find an alternative with the same name in the Object scope
# b) Or use the found mapping
# 2) If not, fallbacks to #{input_type}Input
# 3) If not, fallbacks to SimpleForm::Inputs::#{input_type}Input
def find_mapping(input_type)
discovery_cache[input_type] ||=
if mapping = self.class.mappings[input_type]
mapping_override(mapping) || mapping
else
camelized = "#{input_type.to_s.camelize}Input"
attempt_mapping_with_custom_namespace(camelized) ||
attempt_mapping(camelized, Object) ||
attempt_mapping(camelized, self.class) ||
raise("No input found for #{input_type}")
end
end
# Attempts to find a wrapper mapping. It follows the following rules:
#
# 1) It tries to find a wrapper for the current form
# 2) If not, it tries to find a config
def find_wrapper_mapping(input_type)
if options[:wrapper_mappings] && options[:wrapper_mappings][input_type]
options[:wrapper_mappings][input_type]
else
SimpleForm.wrapper_mappings && SimpleForm.wrapper_mappings[input_type]
end
end
def find_wrapper(input_type, options)
if name = options[:wrapper] || find_wrapper_mapping(input_type)
name.respond_to?(:render) ? name : SimpleForm.wrapper(name)
else
wrapper
end
end
# If cache_discovery is enabled, use the class level cache that persists
# between requests, otherwise use the instance one.
def discovery_cache
if SimpleForm.cache_discovery
self.class.discovery_cache
else
@discovery_cache ||= {}
end
end
def mapping_override(klass)
name = klass.name
if name =~ /^SimpleForm::Inputs/
input_name = name.split("::").last
attempt_mapping_with_custom_namespace(input_name) ||
attempt_mapping(input_name, Object)
end
end
def attempt_mapping(mapping, at)
return if SimpleForm.inputs_discovery == false && at == Object
begin
at.const_get(mapping)
rescue NameError => e
raise unless e.message.include?(mapping)
end
end
def attempt_mapping_with_custom_namespace(input_name)
SimpleForm.custom_inputs_namespaces.each do |namespace|
if (mapping = attempt_mapping(input_name, namespace.constantize))
return mapping
end
end
nil
end
def build_input_field_components(components)
components.map do |component|
if component == :input
SimpleForm::Wrappers::Leaf.new(component, build_input_field_options)
else
SimpleForm::Wrappers::Leaf.new(component)
end
end
end
def build_input_field_options
input_field_options = {}
valid_class = SimpleForm.input_field_valid_class
error_class = SimpleForm.input_field_error_class
if error_class.present?
input_field_options[:error_class] = error_class
end
if valid_class.present?
input_field_options[:valid_class] = valid_class
end
input_field_options
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/wrappers.rb | lib/simple_form/wrappers.rb | # frozen_string_literal: true
module SimpleForm
module Wrappers
autoload :Builder, 'simple_form/wrappers/builder'
autoload :Many, 'simple_form/wrappers/many'
autoload :Root, 'simple_form/wrappers/root'
autoload :Single, 'simple_form/wrappers/single'
autoload :Leaf, 'simple_form/wrappers/leaf'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs.rb | lib/simple_form/inputs.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
extend ActiveSupport::Autoload
autoload :Base
autoload :BlockInput
autoload :BooleanInput
autoload :CollectionCheckBoxesInput
autoload :CollectionInput
autoload :CollectionRadioButtonsInput
autoload :CollectionSelectInput
autoload :ColorInput
autoload :DateTimeInput
autoload :FileInput
autoload :GroupedCollectionSelectInput
autoload :HiddenInput
autoload :NumericInput
autoload :PasswordInput
autoload :PriorityInput
autoload :RangeInput
autoload :RichTextAreaInput
autoload :StringInput
autoload :TextInput
autoload :WeekdayInput
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/tags.rb | lib/simple_form/tags.rb | # frozen_string_literal: true
module SimpleForm
module Tags
module CollectionExtensions
private
def render_collection
item_wrapper_tag = @options.fetch(:item_wrapper_tag, :span)
item_wrapper_class = @options[:item_wrapper_class]
@collection.map do |item|
value = value_for_collection(item, @value_method)
text = value_for_collection(item, @text_method)
default_html_options = default_html_options_for_collection(item, value)
additional_html_options = option_html_attributes(item)
rendered_item = yield item, value, text, default_html_options.merge(additional_html_options)
if @options.fetch(:boolean_style, SimpleForm.boolean_style) == :nested
label_options = default_html_options.slice(:index, :namespace)
label_options['class'] = @options[:item_label_class]
rendered_item = @template_object.label(@object_name, sanitize_attribute_name(value), rendered_item, label_options)
end
item_wrapper_tag ? @template_object.content_tag(item_wrapper_tag, rendered_item, class: item_wrapper_class) : rendered_item
end.join.html_safe
end
def wrap_rendered_collection(collection)
wrapper_tag = @options[:collection_wrapper_tag]
if wrapper_tag
wrapper_class = @options[:collection_wrapper_class]
@template_object.content_tag(wrapper_tag, collection, class: wrapper_class)
else
collection
end
end
end
class CollectionRadioButtons < ActionView::Helpers::Tags::CollectionRadioButtons
include CollectionExtensions
def render
wrap_rendered_collection(super)
end
private
def render_component(builder)
label_class = "#{@options[:item_label_class]} collection_radio_buttons".strip
builder.radio_button + builder.label(class: label_class)
end
end
class CollectionCheckBoxes < ActionView::Helpers::Tags::CollectionCheckBoxes
include CollectionExtensions
def render
wrap_rendered_collection(super)
end
private
def render_component(builder)
label_class = "#{@options[:item_label_class]} collection_check_boxes".strip
builder.check_box + builder.label(class: label_class)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/helpers/autofocus.rb | lib/simple_form/helpers/autofocus.rb | # frozen_string_literal: true
module SimpleForm
module Helpers
module Autofocus
private
def has_autofocus?
options[:autofocus] == true
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/helpers/required.rb | lib/simple_form/helpers/required.rb | # frozen_string_literal: true
module SimpleForm
module Helpers
module Required
private
def required_field?
@required
end
def calculate_required
if !options[:required].nil?
options[:required]
elsif has_validators?
required_by_validators?
else
required_by_default?
end
end
def required_by_validators?
(attribute_validators + reflection_validators).any? { |v| v.kind == :presence && valid_validator?(v) }
end
def required_by_default?
SimpleForm.required_by_default
end
# Do not use has_required? because we want to add the class
# regardless of the required option.
def required_class
required_field? ? :required : :optional
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/helpers/readonly.rb | lib/simple_form/helpers/readonly.rb | # frozen_string_literal: true
module SimpleForm
module Helpers
module Readonly
private
def readonly_class
:readonly if has_readonly?
end
def has_readonly?
options[:readonly] == true
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/helpers/disabled.rb | lib/simple_form/helpers/disabled.rb | # frozen_string_literal: true
module SimpleForm
module Helpers
module Disabled
private
def has_disabled?
options[:disabled] == true
end
def disabled_class
:disabled if has_disabled?
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/helpers/validators.rb | lib/simple_form/helpers/validators.rb | # frozen_string_literal: true
module SimpleForm
module Helpers
module Validators
def has_validators?
@has_validators ||= attribute_name && object.class.respond_to?(:validators_on)
end
private
def attribute_validators
object.class.validators_on(attribute_name)
end
def reflection_validators
reflection ? object.class.validators_on(reflection.name) : []
end
def valid_validator?(validator)
!conditional_validators?(validator) && action_validator_match?(validator)
end
def conditional_validators?(validator)
validator.options.include?(:if) || validator.options.include?(:unless)
end
def action_validator_match?(validator)
return true unless validator.options.include?(:on)
case validator.options[:on]
when :save
true
when :create
!object.persisted?
when :update
object.persisted?
end
end
def find_validator(kind)
attribute_validators.find { |v| v.kind == kind } if has_validators?
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/action_view_extensions/form_helper.rb | lib/simple_form/action_view_extensions/form_helper.rb | # frozen_string_literal: true
module SimpleForm
module ActionViewExtensions
# This module creates SimpleForm wrappers around default form_for and fields_for.
#
# Example:
#
# simple_form_for @user do |f|
# f.input :name, hint: 'My hint'
# end
#
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
if options[:html].key?(:class)
options[:html][:class] = [SimpleForm.form_class, options[:html][:class]].compact
else
options[:html][:class] = [SimpleForm.form_class, SimpleForm.default_form_class, simple_form_css_class(record, options)].compact
end
with_simple_form_field_error_proc do
form_for(record, options, &block)
end
end
def simple_fields_for(record_name, record_object = nil, options = {}, &block)
options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
options[:builder] ||= SimpleForm::FormBuilder
with_simple_form_field_error_proc do
fields_for(record_name, record_object, options, &block)
end
end
private
def with_simple_form_field_error_proc
default_field_error_proc = ::ActionView::Base.field_error_proc
begin
::ActionView::Base.field_error_proc = SimpleForm.field_error_proc
yield
ensure
::ActionView::Base.field_error_proc = default_field_error_proc
end
end
def simple_form_css_class(record, options)
html_options = options[:html]
as = options[:as]
if html_options.key?(:class)
html_options[:class]
elsif record.is_a?(String) || record.is_a?(Symbol)
as || record
else
record = record.last if record.is_a?(Array)
action = record.respond_to?(:persisted?) && record.persisted? ? :edit : :new
as ? "#{action}_#{as}" : dom_class(record, action)
end
end
end
end
end
ActiveSupport.on_load(:action_view) do
include SimpleForm::ActionViewExtensions::FormHelper
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/action_view_extensions/builder.rb | lib/simple_form/action_view_extensions/builder.rb | # frozen_string_literal: true
module SimpleForm
module ActionViewExtensions
# A collection of methods required by simple_form but added to rails default form.
# This means that you can use such methods outside simple_form context.
module Builder
# Wrapper for using SimpleForm inside a default rails form.
# Example:
#
# form_for @user do |f|
# f.simple_fields_for :posts do |posts_form|
# # Here you have all simple_form methods available
# posts_form.input :title
# end
# end
def simple_fields_for(*args, &block)
options = args.extract_options!
options[:wrapper] = self.options[:wrapper] if options[:wrapper].nil?
options[:defaults] ||= self.options[:defaults]
options[:wrapper_mappings] ||= self.options[:wrapper_mappings]
if self.class < ActionView::Helpers::FormBuilder
options[:builder] ||= self.class
else
options[:builder] ||= SimpleForm::FormBuilder
end
fields_for(*args, options, &block)
end
end
end
end
module ActionView::Helpers
class FormBuilder
include SimpleForm::ActionViewExtensions::Builder
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components/maxlength.rb | lib/simple_form/components/maxlength.rb | # frozen_string_literal: true
module SimpleForm
module Components
# Needs to be enabled in order to do automatic lookups.
module Maxlength
def maxlength(wrapper_options = nil)
input_html_options[:maxlength] ||= maximum_length_from_validation || limit
nil
end
private
def maximum_length_from_validation
maxlength = options[:maxlength]
if maxlength.is_a?(String) || maxlength.is_a?(Integer)
maxlength
else
length_validator = find_length_validator
maximum_length_value_from(length_validator)
end
end
def find_length_validator
find_validator(:length)
end
def maximum_length_value_from(length_validator)
if length_validator
length_validator.options[:is] || length_validator.options[:maximum]
end
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components/errors.rb | lib/simple_form/components/errors.rb | # frozen_string_literal: true
module SimpleForm
module Components
module Errors
def error(wrapper_options = nil)
error_text if has_errors?
end
def full_error(wrapper_options = nil)
full_error_text if options[:error] != false && has_errors?
end
def has_errors?
object_with_errors? || !object && has_custom_error?
end
def has_value?
object && object.respond_to?(attribute_name) && object.send(attribute_name).present?
end
def valid?
!has_errors? && has_value?
end
protected
def error_text
text = has_custom_error? ? options[:error] : errors.send(error_method)
"#{html_escape(options[:error_prefix])} #{html_escape(text)}".lstrip.html_safe
end
def full_error_text
has_custom_error? ? options[:error] : full_errors.send(error_method)
end
def object_with_errors?
object && object.respond_to?(:errors) && errors.present?
end
def error_method
options[:error_method] || SimpleForm.error_method
end
def errors
@errors ||= (errors_on_attribute + errors_on_association).compact
end
def full_errors
@full_errors ||= (full_errors_on_attribute + full_errors_on_association).compact
end
def errors_on_attribute
object.errors[attribute_name] || []
end
def full_errors_on_attribute
object.errors.full_messages_for(attribute_name)
end
def errors_on_association
reflection ? object.errors[reflection.name] : []
end
def full_errors_on_association
reflection ? object.errors.full_messages_for(reflection.name) : []
end
def has_custom_error?
options[:error].is_a?(String)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components/readonly.rb | lib/simple_form/components/readonly.rb | # frozen_string_literal: true
module SimpleForm
module Components
# Needs to be enabled in order to do automatic lookups.
module Readonly
def readonly(wrapper_options = nil)
if readonly_attribute? && !has_readonly?
input_html_options[:readonly] ||= true
input_html_classes << :readonly
end
nil
end
private
def readonly_attribute?
object.class.respond_to?(:readonly_attributes) &&
object.persisted? &&
object.class.readonly_attributes.include?(attribute_name.to_s)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components/html5.rb | lib/simple_form/components/html5.rb | # frozen_string_literal: true
module SimpleForm
module Components
module HTML5
def initialize(*)
@html5 = false
end
def html5(wrapper_options = nil)
@html5 = true
input_html_options[:required] = input_html_required_option
input_html_options[:'aria-invalid'] = has_errors? || nil
nil
end
def html5?
@html5
end
def input_html_required_option
!options[:required].nil? ? required_field? : has_required?
end
def has_required?
# We need to check browser_validations because
# some browsers are still checking required even
# if novalidate was given.
required_field? && SimpleForm.browser_validations
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components/min_max.rb | lib/simple_form/components/min_max.rb | # frozen_string_literal: true
module SimpleForm
module Components
module MinMax
def min_max(wrapper_options = nil)
if numeric_validator = find_numericality_validator
validator_options = numeric_validator.options
input_html_options[:min] ||= minimum_value(validator_options)
input_html_options[:max] ||= maximum_value(validator_options)
end
nil
end
private
def integer?
input_type == :integer
end
def minimum_value(validator_options)
if integer? && validator_options.key?(:greater_than)
evaluate_numericality_validator_option(validator_options[:greater_than]) + 1
else
evaluate_numericality_validator_option(validator_options[:greater_than_or_equal_to])
end
end
def maximum_value(validator_options)
if integer? && validator_options.key?(:less_than)
evaluate_numericality_validator_option(validator_options[:less_than]) - 1
else
evaluate_numericality_validator_option(validator_options[:less_than_or_equal_to])
end
end
def find_numericality_validator
find_validator(:numericality)
end
def evaluate_numericality_validator_option(option)
if option.is_a?(Numeric)
option
elsif option.is_a?(Symbol)
object.send(option)
elsif option.respond_to?(:call)
option.call(object)
end
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components/placeholders.rb | lib/simple_form/components/placeholders.rb | # frozen_string_literal: true
module SimpleForm
module Components
# Needs to be enabled in order to do automatic lookups.
module Placeholders
def placeholder(wrapper_options = nil)
input_html_options[:placeholder] ||= placeholder_text
nil
end
def placeholder_text(wrapper_options = nil)
placeholder = options[:placeholder]
placeholder.is_a?(String) ? placeholder : translate_from_namespace(:placeholders)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components/hints.rb | lib/simple_form/components/hints.rb | # frozen_string_literal: true
module SimpleForm
module Components
# Needs to be enabled in order to do automatic lookups.
module Hints
def hint(wrapper_options = nil)
@hint ||= begin
hint = options[:hint]
if hint.is_a?(String)
html_escape(hint)
else
content = translate_from_namespace(:hints)
content.html_safe if content
end
end
end
def has_hint?
options[:hint] != false && hint.present?
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components/label_input.rb | lib/simple_form/components/label_input.rb | # frozen_string_literal: true
module SimpleForm
module Components
module LabelInput
extend ActiveSupport::Concern
included do
include SimpleForm::Components::Labels
end
def label_input(wrapper_options = nil)
if options[:label] == false
deprecated_component(:input, wrapper_options)
else
deprecated_component(:label, wrapper_options) + deprecated_component(:input, wrapper_options)
end
end
private
def deprecated_component(namespace, wrapper_options)
method = method(namespace)
if method.arity.zero?
SimpleForm.deprecator.warn(SimpleForm::CUSTOM_INPUT_DEPRECATION_WARN % { name: namespace })
method.call
else
method.call(wrapper_options)
end
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components/pattern.rb | lib/simple_form/components/pattern.rb | # frozen_string_literal: true
module SimpleForm
module Components
# Needs to be enabled in order to do automatic lookups.
module Pattern
def pattern(wrapper_options = nil)
input_html_options[:pattern] ||= pattern_source
nil
end
private
def pattern_source
pattern = options[:pattern]
if pattern.is_a?(String)
pattern
elsif (pattern_validator = find_pattern_validator) && (with = pattern_validator.options[:with])
evaluate_format_validator_option(with).source
end
end
def find_pattern_validator
find_validator(:format)
end
def evaluate_format_validator_option(option)
if option.respond_to?(:call)
option.call(object)
else
option
end
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components/minlength.rb | lib/simple_form/components/minlength.rb | # frozen_string_literal: true
module SimpleForm
module Components
# Needs to be enabled in order to do automatic lookups.
module Minlength
def minlength(wrapper_options = nil)
input_html_options[:minlength] ||= minimum_length_from_validation
nil
end
private
def minimum_length_from_validation
minlength = options[:minlength]
if minlength.is_a?(String) || minlength.is_a?(Integer)
minlength
else
length_validator = find_length_validator
minimum_length_value_from(length_validator)
end
end
def find_length_validator
find_validator(:length)
end
def minimum_length_value_from(length_validator)
if length_validator
length_validator.options[:is] || length_validator.options[:minimum]
end
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components/labels.rb | lib/simple_form/components/labels.rb | # frozen_string_literal: true
module SimpleForm
module Components
module Labels
extend ActiveSupport::Concern
module ClassMethods #:nodoc:
def translate_required_html
I18n.t(:"required.html", scope: i18n_scope, default:
%(<abbr title="#{translate_required_text}">#{translate_required_mark}</abbr>)
)
end
def translate_required_text
I18n.t(:"required.text", scope: i18n_scope, default: 'required')
end
def translate_required_mark
I18n.t(:"required.mark", scope: i18n_scope, default: '*')
end
private
def i18n_scope
SimpleForm.i18n_scope
end
end
def label(wrapper_options = nil)
label_options = merge_wrapper_options(label_html_options, wrapper_options)
if generate_label_for_attribute?
@builder.label(label_target, label_text, label_options)
else
template.label_tag(nil, label_text, label_options)
end
end
def label_text(wrapper_options = nil)
label_text = options[:label_text] || SimpleForm.label_text
label_text.call(html_escape(raw_label_text), required_label_text, options[:label].present?).strip.html_safe
end
def label_target
attribute_name
end
def label_html_options
label_html_classes = SimpleForm.additional_classes_for(:label) {
[input_type, required_class, disabled_class, SimpleForm.label_class].compact
}
label_options = html_options_for(:label, label_html_classes)
if options.key?(:input_html) && options[:input_html].key?(:id)
label_options[:for] = options[:input_html][:id]
end
label_options
end
protected
def raw_label_text #:nodoc:
options[:label] || label_translation
end
# Default required text when attribute is required.
def required_label_text #:nodoc:
required_field? ? self.class.translate_required_html.dup : ''
end
# First check labels translation and then human attribute name.
def label_translation #:nodoc:
if SimpleForm.translate_labels && (translated_label = translate_from_namespace(:labels))
translated_label
elsif object.class.respond_to?(:human_attribute_name)
object.class.human_attribute_name(reflection_or_attribute_name.to_s, { base: object })
else
attribute_name.to_s.humanize
end
end
def generate_label_for_attribute?
true
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/wrappers/single.rb | lib/simple_form/wrappers/single.rb | # frozen_string_literal: true
module SimpleForm
module Wrappers
# `Single` is an optimization for a wrapper that has only one component.
class Single < Many
def initialize(name, wrapper_options = {}, options = {})
@component = Leaf.new(name, options)
super(name, [@component], wrapper_options)
end
def render(input)
options = input.options
if options[namespace] != false
content = @component.render(input)
wrap(input, options, content) if content
end
end
private
def html_options(options)
%i[label input].include?(namespace) ? {} : super
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/wrappers/leaf.rb | lib/simple_form/wrappers/leaf.rb | # frozen_string_literal: true
module SimpleForm
module Wrappers
class Leaf
attr_reader :namespace
def initialize(namespace, options = {})
@namespace = namespace
@options = options
end
def render(input)
method = input.method(@namespace)
if method.arity.zero?
SimpleForm.deprecator.warn(SimpleForm::CUSTOM_INPUT_DEPRECATION_WARN % { name: @namespace })
method.call
else
method.call(@options)
end
end
def find(name)
self if @namespace == name
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/wrappers/root.rb | lib/simple_form/wrappers/root.rb | # frozen_string_literal: true
module SimpleForm
module Wrappers
# `Root` is the root wrapper for all components. It is special cased to
# always have a namespace and to add special html classes.
class Root < Many
attr_reader :options
def initialize(*args)
super(:wrapper, *args)
@options = @defaults.except(:tag, :class, :error_class, :hint_class)
end
def render(input)
input.options.reverse_merge!(@options)
super
end
# Provide a fallback if name cannot be found.
def find(name)
super || SimpleForm::Wrappers::Many.new(name, [Leaf.new(name)])
end
private
def html_classes(input, options)
css = options[:wrapper_class] ? Array(options[:wrapper_class]) : @defaults[:class]
css += SimpleForm.additional_classes_for(:wrapper) do
input.additional_classes + [input.input_class]
end
css << html_class(:error_class, options) { input.has_errors? }
css << html_class(:hint_class, options) { input.has_hint? }
css << html_class(:valid_class, options) { input.valid? }
css.compact
end
def html_class(key, options)
css = (options[:"wrapper_#{key}"] || @defaults[key])
css if css && yield
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/wrappers/many.rb | lib/simple_form/wrappers/many.rb | # frozen_string_literal: true
module SimpleForm
module Wrappers
# A wrapper is an object that holds several components and render them.
# A component may be any object that responds to `render`.
# This API allows inputs/components to be easily wrapped, removing the
# need to modify the code only to wrap input in an extra tag.
#
# `Many` represents a wrapper around several components at the same time.
# It may optionally receive a namespace, allowing it to be configured
# on demand on input generation.
class Many
attr_reader :namespace, :defaults, :components
def initialize(namespace, components, defaults = {})
@namespace = namespace
@components = components
@defaults = defaults
@defaults[:tag] = :div unless @defaults.key?(:tag)
@defaults[:class] = Array(@defaults[:class])
end
def render(input)
content = "".html_safe
options = input.options
components.each do |component|
next if options[component.namespace] == false
rendered = component.render(input)
content.safe_concat rendered.to_s if rendered
end
wrap(input, options, content)
end
def find(name)
return self if namespace == name
@components.each do |c|
if c.is_a?(Symbol)
return nil if c == namespace
elsif value = c.find(name)
return value
end
end
nil
end
private
def wrap(input, options, content)
return content if options[namespace] == false
return if defaults[:unless_blank] && content.empty?
tag = (namespace && options[:"#{namespace}_tag"]) || @defaults[:tag]
return content unless tag
klass = html_classes(input, options)
opts = html_options(options)
opts[:class] = (klass << opts[:class]).join(' ').strip unless klass.empty?
input.template.content_tag(tag, content, opts)
end
def html_options(options)
(@defaults[:html] || {}).merge(options[:"#{namespace}_html"] || {})
end
def html_classes(input, options)
@defaults[:class].dup
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/wrappers/builder.rb | lib/simple_form/wrappers/builder.rb | # frozen_string_literal: true
module SimpleForm
module Wrappers
# Provides the builder syntax for components. The builder provides
# three methods `use`, `optional` and `wrapper` and they allow the following invocations:
#
# config.wrappers do |b|
# # Use a single component
# b.use :html5
#
# # Use the component, but do not automatically lookup. It will only be triggered when
# # :placeholder is explicitly set.
# b.optional :placeholder
#
# # Use a component with specific wrapper options
# b.use :error, wrap_with: { tag: "span", class: "error" }
#
# # Use a set of components by wrapping them in a tag+class.
# b.wrapper tag: "div", class: "another" do |ba|
# ba.use :label
# ba.use :input
# end
#
# # Use a set of components by wrapping them in a tag+class.
# # This wrapper is identified by :label_input, which means it can
# # be turned off on demand with `f.input :name, label_input: false`
# b.wrapper :label_input, tag: "div", class: "another" do |ba|
# ba.use :label
# ba.use :input
# end
# end
#
# The builder also accepts default options at the root level. This is usually
# used if you want a component to be disabled by default:
#
# config.wrappers hint: false do |b|
# b.use :hint
# b.use :label_input
# end
#
# In the example above, hint defaults to false, which means it won't automatically
# do the lookup anymore. It will only be triggered when :hint is explicitly set.
class Builder
def initialize(options)
@options = options
@components = []
end
def use(name, options = {})
if options && wrapper = options[:wrap_with]
@components << Single.new(name, wrapper, options.except(:wrap_with))
else
@components << Leaf.new(name, options)
end
end
def optional(name, options = {}, &block)
@options[name] = false
use(name, options)
end
def wrapper(name, options = nil)
if block_given?
name, options = nil, name if name.is_a?(Hash)
builder = self.class.new(@options)
options ||= {}
options[:tag] = :div if options[:tag].nil?
yield builder
@components << Many.new(name, builder.to_a, options)
else
raise ArgumentError, "A block is required as argument to wrapper"
end
end
def to_a
@components
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/rich_text_area_input.rb | lib/simple_form/inputs/rich_text_area_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class RichTextAreaInput < Base
enable :placeholder
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.rich_text_area(attribute_name, merged_input_options)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/string_input.rb | lib/simple_form/inputs/string_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class StringInput < Base
enable :placeholder, :maxlength, :minlength, :pattern
def input(wrapper_options = nil)
unless string?
input_html_classes.unshift("string")
input_html_options[:type] ||= input_type if html5?
end
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.text_field(attribute_name, merged_input_options)
end
private
def string?
input_type == :string || input_type == :citext
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/block_input.rb | lib/simple_form/inputs/block_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class BlockInput < Base
def initialize(*args, &block)
super
@block = block
end
def input(wrapper_options = nil)
template.capture(&@block)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/range_input.rb | lib/simple_form/inputs/range_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class RangeInput < NumericInput
def input(wrapper_options = nil)
if html5?
input_html_options[:type] ||= "range"
input_html_options[:step] ||= 1
end
super
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/priority_input.rb | lib/simple_form/inputs/priority_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class PriorityInput < CollectionSelectInput
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
send(:"#{input_type}_input", merged_input_options)
end
def input_priority
options[:priority] || SimpleForm.send(:"#{input_type}_priority")
end
protected
def country_input(merged_input_options)
@builder.send(:country_select,
attribute_name,
input_options.merge(priority_countries: input_priority),
merged_input_options)
end
def time_zone_input(merged_input_options)
@builder.send(:time_zone_select,
attribute_name,
input_priority,
input_options,
merged_input_options)
end
def skip_include_blank?
super || input_priority.present?
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/color_input.rb | lib/simple_form/inputs/color_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class ColorInput < Base
def input(wrapper_options = nil)
input_html_options[:type] ||= "color" if html5?
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.text_field(attribute_name, merged_input_options)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/collection_select_input.rb | lib/simple_form/inputs/collection_select_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class CollectionSelectInput < CollectionInput
def input(wrapper_options = nil)
label_method, value_method = detect_collection_methods
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.collection_select(
attribute_name, collection, value_method, label_method,
input_options, merged_input_options
)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/collection_radio_buttons_input.rb | lib/simple_form/inputs/collection_radio_buttons_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class CollectionRadioButtonsInput < CollectionInput
def input(wrapper_options = nil)
label_method, value_method = detect_collection_methods
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.send(:"collection_#{input_type}",
attribute_name, collection, value_method, label_method,
input_options, merged_input_options,
&collection_block_for_nested_boolean_style
)
end
def input_options
options = super
apply_default_collection_options!(options)
options
end
protected
def apply_default_collection_options!(options)
options[:item_wrapper_tag] ||= options.fetch(:item_wrapper_tag, SimpleForm.item_wrapper_tag)
options[:item_wrapper_class] = [
item_wrapper_class, options[:item_wrapper_class], SimpleForm.item_wrapper_class
].compact.presence if SimpleForm.include_default_input_wrapper_class
options[:collection_wrapper_tag] ||= options.fetch(:collection_wrapper_tag, SimpleForm.collection_wrapper_tag)
options[:collection_wrapper_class] = [
options[:collection_wrapper_class], SimpleForm.collection_wrapper_class
].compact.presence
end
def collection_block_for_nested_boolean_style
return unless nested_boolean_style?
proc { |builder| build_nested_boolean_style_item_tag(builder) }
end
def build_nested_boolean_style_item_tag(collection_builder)
collection_builder.radio_button + collection_builder.text.to_s
end
def item_wrapper_class
"radio"
end
# Do not attempt to generate label[for] attributes by default, unless an
# explicit html option is given. This avoids generating labels pointing to
# non existent fields.
def generate_label_for_attribute?
false
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/date_time_input.rb | lib/simple_form/inputs/date_time_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class DateTimeInput < Base
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
if use_html5_inputs?
@builder.send(:"#{input_type}_field", attribute_name, merged_input_options)
else
@builder.send(:"#{input_type}_select", attribute_name, input_options, merged_input_options)
end
end
private
def label_target
if use_html5_inputs?
attribute_name
else
position = case input_type
when :date, :datetime
date_order = input_options[:order] || I18n.t('date.order')
date_order.first.to_sym
else
:hour
end
position = ActionView::Helpers::DateTimeSelector::POSITION[position]
"#{attribute_name}_#{position}i"
end
end
def use_html5_inputs?
input_options[:html5]
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/base.rb | lib/simple_form/inputs/base.rb | # frozen_string_literal: true
require 'active_support/core_ext/string/output_safety'
require 'action_view/helpers'
module SimpleForm
module Inputs
class Base
include ERB::Util
include ActionView::Helpers::TranslationHelper
include SimpleForm::Helpers::Autofocus
include SimpleForm::Helpers::Disabled
include SimpleForm::Helpers::Readonly
include SimpleForm::Helpers::Required
include SimpleForm::Helpers::Validators
include SimpleForm::Components::Errors
include SimpleForm::Components::Hints
include SimpleForm::Components::HTML5
include SimpleForm::Components::LabelInput
include SimpleForm::Components::Maxlength
include SimpleForm::Components::Minlength
include SimpleForm::Components::MinMax
include SimpleForm::Components::Pattern
include SimpleForm::Components::Placeholders
include SimpleForm::Components::Readonly
attr_reader :attribute_name, :column, :input_type, :reflection,
:options, :input_html_options, :input_html_classes, :html_classes
delegate :template, :object, :object_name, :lookup_model_names, :lookup_action, to: :@builder
class_attribute :default_options
self.default_options = {}
def self.enable(*keys)
options = self.default_options.dup
keys.each { |key| options.delete(key) }
self.default_options = options
end
def self.disable(*keys)
options = self.default_options.dup
keys.each { |key| options[key] = false }
self.default_options = options
end
# Always enabled.
enable :hint
# Usually disabled, needs to be enabled explicitly passing true as option.
disable :maxlength, :minlength, :placeholder, :pattern, :min_max
def initialize(builder, attribute_name, column, input_type, options = {})
super
options = options.dup
@builder = builder
@attribute_name = attribute_name
@column = column
@input_type = input_type
@reflection = options.delete(:reflection)
@options = options.reverse_merge!(self.class.default_options)
@required = calculate_required
# Notice that html_options_for receives a reference to input_html_classes.
# This means that classes added dynamically to input_html_classes will
# still propagate to input_html_options.
@html_classes = SimpleForm.additional_classes_for(:input) { additional_classes }
@input_html_classes = @html_classes.dup
input_html_classes = self.input_html_classes
if SimpleForm.input_class && input_html_classes.any?
input_html_classes << SimpleForm.input_class
end
@input_html_options = html_options_for(:input, input_html_classes).tap do |o|
o[:readonly] = true if has_readonly?
o[:disabled] = true if has_disabled?
o[:autofocus] = true if has_autofocus?
end
end
def input(wrapper_options = nil)
raise NotImplementedError
end
def input_options
options
end
def additional_classes
@additional_classes ||= [input_type, required_class, readonly_class, disabled_class].compact
end
def input_class
"#{lookup_model_names.join('_')}_#{reflection_or_attribute_name}"
end
private
def limit
if column
decimal_or_float? ? decimal_limit : column_limit
end
end
def column_limit
column.limit
end
# Add one for decimal point
def decimal_limit
column_limit && (column_limit + 1)
end
def decimal_or_float?
column.type == :float || column.type == :decimal
end
def nested_boolean_style?
options.fetch(:boolean_style, SimpleForm.boolean_style) == :nested
end
# Find reflection name when available, otherwise use attribute
def reflection_or_attribute_name
@reflection_or_attribute_name ||= reflection ? reflection.name : attribute_name
end
# Retrieve options for the given namespace from the options hash
def html_options_for(namespace, css_classes)
html_options = options[:"#{namespace}_html"]
html_options = html_options ? html_options.dup : {}
css_classes << html_options[:class] if html_options.key?(:class)
html_options[:class] = css_classes unless css_classes.empty?
html_options
end
# Lookup translations for the given namespace using I18n, based on object name,
# actual action and attribute name. Lookup priority as follows:
#
# simple_form.{namespace}.{model}.{action}.{attribute}
# simple_form.{namespace}.{model}.{attribute}
# simple_form.{namespace}.defaults.{attribute}
#
# Namespace is used for :labels and :hints.
#
# Model is the actual object name, for a @user object you'll have :user.
# Action is the action being rendered, usually :new or :edit.
# And attribute is the attribute itself, :name for example.
#
# The lookup for nested attributes is also done in a nested format using
# both model and nested object names, such as follow:
#
# simple_form.{namespace}.{model}.{nested}.{action}.{attribute}
# simple_form.{namespace}.{model}.{nested}.{attribute}
# simple_form.{namespace}.{nested}.{action}.{attribute}
# simple_form.{namespace}.{nested}.{attribute}
# simple_form.{namespace}.defaults.{attribute}
#
# Example:
#
# simple_form:
# labels:
# user:
# new:
# email: 'E-mail para efetuar o sign in.'
# edit:
# email: 'E-mail.'
#
# Take a look at our locale example file.
def translate_from_namespace(namespace, default = '')
model_names = lookup_model_names.dup
lookups = []
while !model_names.empty?
joined_model_names = model_names.join(".")
model_names.shift
lookups << :"#{joined_model_names}.#{lookup_action}.#{reflection_or_attribute_name}"
lookups << :"#{joined_model_names}.#{reflection_or_attribute_name}"
end
lookups << :"defaults.#{lookup_action}.#{reflection_or_attribute_name}"
lookups << :"defaults.#{reflection_or_attribute_name}"
lookups << default
I18n.t(lookups.shift, scope: :"#{i18n_scope}.#{namespace}", default: lookups).presence
end
def merge_wrapper_options(options, wrapper_options)
if wrapper_options
wrapper_options = set_input_classes(wrapper_options)
wrapper_options.merge(options) do |key, oldval, newval|
case key.to_s
when "class"
Array(oldval) + Array(newval)
when "data", "aria"
oldval.merge(newval)
else
newval
end
end
else
options
end
end
def set_input_classes(wrapper_options)
wrapper_options = wrapper_options.dup
error_class = wrapper_options.delete(:error_class)
valid_class = wrapper_options.delete(:valid_class)
if error_class.present? && has_errors?
wrapper_options[:class] = "#{wrapper_options[:class]} #{error_class}"
end
if valid_class.present? && valid?
wrapper_options[:class] = "#{wrapper_options[:class]} #{valid_class}"
end
wrapper_options
end
def i18n_scope
SimpleForm.i18n_scope
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/collection_check_boxes_input.rb | lib/simple_form/inputs/collection_check_boxes_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class CollectionCheckBoxesInput < CollectionRadioButtonsInput
protected
# Checkbox components do not use the required html tag.
# More info: https://github.com/heartcombo/simple_form/issues/340#issuecomment-2871956
def has_required?
false
end
def build_nested_boolean_style_item_tag(collection_builder)
collection_builder.check_box + collection_builder.text.to_s
end
def item_wrapper_class
"checkbox"
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/numeric_input.rb | lib/simple_form/inputs/numeric_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class NumericInput < Base
enable :placeholder, :min_max
def input(wrapper_options = nil)
input_html_classes.unshift("numeric")
if html5?
input_html_options[:type] ||= "number"
input_html_options[:step] ||= integer? ? 1 : "any"
end
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.text_field(attribute_name, merged_input_options)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/boolean_input.rb | lib/simple_form/inputs/boolean_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class BooleanInput < Base
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
if nested_boolean_style?
build_hidden_field_for_checkbox +
template.label_tag(nil, class: boolean_label_class) {
build_check_box_without_hidden_field(merged_input_options) +
inline_label
}
else
if include_hidden?
build_check_box(unchecked_value, merged_input_options)
else
build_check_box_without_hidden_field(merged_input_options)
end
end
end
def label_input(wrapper_options = nil)
if options[:label] == false || inline_label?
input(wrapper_options)
elsif nested_boolean_style?
html_options = label_html_options.dup
html_options[:class] ||= []
html_options[:class].push(boolean_label_class) if boolean_label_class
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
build_hidden_field_for_checkbox +
@builder.label(label_target, html_options) {
build_check_box_without_hidden_field(merged_input_options) + label_text
}
else
input(wrapper_options) + label(wrapper_options)
end
end
private
def boolean_label_class
options[:boolean_label_class] || SimpleForm.boolean_label_class
end
# Build a checkbox tag using default unchecked value. This allows us to
# reuse the method for nested boolean style, but with no unchecked value,
# which won't generate the hidden checkbox. This is the default functionality
# in Rails > 3.2.1, and is backported in SimpleForm AV helpers.
def build_check_box(unchecked_value, options)
@builder.check_box(attribute_name, options, checked_value, unchecked_value)
end
# Build a checkbox without generating the hidden field. See
# #build_hidden_field_for_checkbox for more info.
def build_check_box_without_hidden_field(options)
build_check_box(nil, options)
end
# Create a hidden field for the current checkbox, so we can simulate Rails
# functionality with hidden + checkbox, but under a nested context, where
# we need the hidden field to be *outside* the label (otherwise it
# generates invalid html - html5 only).
def build_hidden_field_for_checkbox
return "".html_safe if !include_hidden? || !unchecked_value
options = { value: unchecked_value, id: nil, disabled: input_html_options[:disabled] }
options[:name] = input_html_options[:name] if input_html_options.key?(:name)
options[:form] = input_html_options[:form] if input_html_options.key?(:form)
@builder.hidden_field(attribute_name, options)
end
def inline_label?
nested_boolean_style? && options[:inline_label]
end
def inline_label
inline_option = options[:inline_label]
if inline_option
label = inline_option == true ? label_text : html_escape(inline_option)
" #{label}".html_safe
end
end
# Booleans are not required by default because in most of the cases
# it makes no sense marking them as required. The only exception is
# Terms of Use usually presented at most sites sign up screen.
def required_by_default?
false
end
def include_hidden?
options.fetch(:include_hidden, true)
end
def checked_value
options.fetch(:checked_value, '1')
end
def unchecked_value
options.fetch(:unchecked_value, '0')
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/collection_input.rb | lib/simple_form/inputs/collection_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class CollectionInput < Base
BASIC_OBJECT_CLASSES = [String, Integer, Float, NilClass, Symbol, TrueClass, FalseClass]
BASIC_OBJECT_CLASSES.push(Fixnum, Bignum) unless 1.class == Integer
# Default boolean collection for use with selects/radios when no
# collection is given. Always fallback to this boolean collection.
# Texts can be translated using i18n in "simple_form.yes" and
# "simple_form.no" keys. See the example locale file.
def self.boolean_collection
[ [I18n.t(:"simple_form.yes", default: 'Yes'), true],
[I18n.t(:"simple_form.no", default: 'No'), false] ]
end
def input(wrapper_options = nil)
raise NotImplementedError,
"input should be implemented by classes inheriting from CollectionInput"
end
def input_options
options = super
options[:include_blank] = true unless skip_include_blank?
translate_option options, :prompt
translate_option options, :include_blank
options
end
private
def collection
@collection ||= begin
collection = options.delete(:collection) || self.class.boolean_collection
collection.respond_to?(:call) ? collection.call : collection.to_a
end
end
def has_required?
super && (input_options[:include_blank] || input_options[:prompt].present? || multiple?)
end
# Check if :include_blank must be included by default.
def skip_include_blank?
(options.keys & %i[prompt include_blank default selected]).any? || multiple?
end
def multiple?
!!options[:input_html].try(:[], :multiple)
end
# Detect the right method to find the label and value for a collection.
# If no label or value method are defined, will attempt to find them based
# on default label and value methods that can be configured through
# SimpleForm.collection_label_methods and
# SimpleForm.collection_value_methods.
def detect_collection_methods
label, value = options.delete(:label_method), options.delete(:value_method)
unless label && value
common_method_for = detect_common_display_methods
label ||= common_method_for[:label]
value ||= common_method_for[:value]
end
[label, value]
end
def detect_common_display_methods(collection_classes = detect_collection_classes)
collection_translated = translate_collection if collection_classes == [Symbol]
if collection_translated || collection_classes.include?(Array)
{ label: :first, value: :second }
elsif collection_includes_basic_objects?(collection_classes)
{ label: :to_s, value: :to_s }
else
detect_method_from_class(collection_classes)
end
end
def detect_method_from_class(collection_classes)
sample = collection.first || collection.last
{ label: SimpleForm.collection_label_methods.find { |m| sample.respond_to?(m) },
value: SimpleForm.collection_value_methods.find { |m| sample.respond_to?(m) } }
end
def detect_collection_classes(some_collection = collection)
some_collection.map(&:class).uniq
end
def collection_includes_basic_objects?(collection_classes)
(collection_classes & BASIC_OBJECT_CLASSES).any?
end
def translate_collection
if translated_collection = translate_from_namespace(:options)
@collection = collection.map do |key|
html_key = "#{key}_html".to_sym
if translated_collection[html_key]
[translated_collection[html_key].html_safe || key, key.to_s]
else
[translated_collection[key] || key, key.to_s]
end
end
true
end
end
def translate_option(options, key)
if options[key] == :translate
namespace = key.to_s.pluralize
options[key] = translate_from_namespace(namespace, true)
end
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/file_input.rb | lib/simple_form/inputs/file_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class FileInput < Base
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.file_field(attribute_name, merged_input_options)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/password_input.rb | lib/simple_form/inputs/password_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class PasswordInput < Base
enable :placeholder, :maxlength, :minlength
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.password_field(attribute_name, merged_input_options)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/hidden_input.rb | lib/simple_form/inputs/hidden_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class HiddenInput < Base
disable :label, :errors, :hint, :required
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.hidden_field(attribute_name, merged_input_options)
end
private
def required_class
nil
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/grouped_collection_select_input.rb | lib/simple_form/inputs/grouped_collection_select_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class GroupedCollectionSelectInput < CollectionInput
def input(wrapper_options = nil)
label_method, value_method = detect_collection_methods
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.grouped_collection_select(attribute_name, grouped_collection,
group_method, group_label_method, value_method, label_method,
input_options, merged_input_options)
end
private
def grouped_collection
@grouped_collection ||= begin
grouped_collection = options.delete(:collection)
grouped_collection.respond_to?(:call) ? grouped_collection.call : grouped_collection.to_a
end
end
# Sample collection
def collection
@collection ||= grouped_collection.map { |collection| group_method.respond_to?(:call) ? group_method.call(collection) : collection.try(:send, group_method) }.detect(&:present?) || []
end
def group_method
@group_method ||= options.delete(:group_method)
end
def group_label_method
label = options.delete(:group_label_method)
unless label
common_method_for = detect_common_display_methods(detect_collection_classes(grouped_collection))
label = common_method_for[:label]
end
label
end
def detect_method_from_class(collection_classes)
return {} if collection_classes.empty?
sample = collection_classes.first
{ label: SimpleForm.collection_label_methods.find { |m| sample.instance_methods.include?(m) },
value: SimpleForm.collection_value_methods.find { |m| sample.instance_methods.include?(m) } }
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/text_input.rb | lib/simple_form/inputs/text_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class TextInput < Base
enable :placeholder, :maxlength, :minlength
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.text_area(attribute_name, merged_input_options)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/inputs/weekday_input.rb | lib/simple_form/inputs/weekday_input.rb | # frozen_string_literal: true
module SimpleForm
module Inputs
class WeekdayInput < CollectionSelectInput
enable :placeholder
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.weekday_select(attribute_name, input_options, merged_input_options)
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/generators/simple_form/install_generator.rb | lib/generators/simple_form/install_generator.rb | # frozen_string_literal: true
module SimpleForm
module Generators
class InstallGenerator < Rails::Generators::Base
desc "Copy SimpleForm default files"
source_root File.expand_path('../templates', __FILE__)
class_option :template_engine, desc: 'Template engine to be invoked (erb, haml or slim).'
class_option :bootstrap, type: :boolean, desc: 'Add the Bootstrap 5 wrappers to the SimpleForm initializer.'
class_option :foundation, type: :boolean, desc: 'Add the Zurb Foundation 5 wrappers to the SimpleForm initializer.'
def info_bootstrap
return if options.bootstrap? || options.foundation?
puts "SimpleForm supports Bootstrap 5 and Zurb Foundation 5. If you want "\
"a configuration that is compatible with one of these frameworks, then please " \
"re-run this generator with --bootstrap or --foundation as an option."
end
def copy_config
template "config/initializers/simple_form.rb"
if options[:bootstrap]
template "config/initializers/simple_form_bootstrap.rb"
elsif options[:foundation]
template "config/initializers/simple_form_foundation.rb"
end
directory 'config/locales'
end
def copy_scaffold_template
engine = options[:template_engine]
copy_file "_form.html.#{engine}", "lib/templates/#{engine}/scaffold/_form.html.#{engine}"
end
def show_readme
if behavior == :invoke && options.bootstrap?
readme "README"
end
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/generators/simple_form/templates/config/initializers/simple_form_foundation.rb | lib/generators/simple_form/templates/config/initializers/simple_form_foundation.rb | # frozen_string_literal: true
#
# Uncomment this and change the path if necessary to include your own
# components.
# See https://github.com/heartcombo/simple_form#custom-components to know
# more about custom components.
# Dir[Rails.root.join('lib/components/**/*.rb')].each { |f| require f }
#
# Use this setup block to configure all options available in SimpleForm.
SimpleForm.setup do |config|
# Don't forget to edit this file to adapt it to your needs (specially
# all the grid-related classes)
#
# Please note that hints are commented out by default since Foundation
# doesn't provide styles for hints. You will need to provide your own CSS styles for hints.
# Uncomment them to enable hints.
config.wrappers :vertical_form, class: :input, hint_class: :field_with_hint, error_class: :error, valid_class: :valid do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :minlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label_input
b.use :error, wrap_with: { tag: :small, class: :error }
# b.use :hint, wrap_with: { tag: :span, class: :hint }
end
config.wrappers :horizontal_form, tag: 'div', class: 'row', hint_class: :field_with_hint, error_class: :error, valid_class: :valid do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :minlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.wrapper :label_wrapper, tag: :div, class: 'small-3 columns' do |ba|
ba.use :label, class: 'text-right inline'
end
b.wrapper :right_input_wrapper, tag: :div, class: 'small-9 columns' do |ba|
ba.use :input
ba.use :error, wrap_with: { tag: :small, class: :error }
# ba.use :hint, wrap_with: { tag: :span, class: :hint }
end
end
config.wrappers :horizontal_radio_and_checkboxes, tag: 'div', class: 'row' do |b|
b.use :html5
b.optional :readonly
b.wrapper :container_wrapper, tag: 'div', class: 'small-offset-3 small-9 columns' do |ba|
ba.wrapper tag: 'label', class: 'checkbox' do |bb|
bb.use :input
bb.use :label_text
end
ba.use :error, wrap_with: { tag: :small, class: :error }
# ba.use :hint, wrap_with: { tag: :span, class: :hint }
end
end
# Foundation does not provide a way to handle inline forms
# This wrapper can be used to create an inline form
# by hiding that labels on every screen sizes ('hidden-for-small-up').
#
# Note that you need to adapt this wrapper to your needs. If you need a 4
# columns form then change the wrapper class to 'small-3', if you need
# only two use 'small-6' and so on.
config.wrappers :inline_form, tag: 'div', class: 'column small-4', hint_class: :field_with_hint, error_class: :error, valid_class: :valid do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :minlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label, class: 'hidden-for-small-up'
b.use :input
b.use :error, wrap_with: { tag: :small, class: :error }
# b.use :hint, wrap_with: { tag: :span, class: :hint }
end
# Examples of use:
# - wrapper_html: {class: 'row'}, custom_wrapper_html: {class: 'column small-12'}
# - custom_wrapper_html: {class: 'column small-3 end'}
config.wrappers :customizable_wrapper, tag: 'div', error_class: :error, valid_class: :valid do |b|
b.use :html5
b.optional :readonly
b.wrapper :custom_wrapper, tag: :div do |ba|
ba.use :label_input
end
b.use :error, wrap_with: { tag: :small, class: :error }
# b.use :hint, wrap_with: { tag: :span, class: :hint }
end
# CSS class for buttons
config.button_class = 'button'
# Set this to div to make the checkbox and radio properly work
# otherwise simple_form adds a label tag instead of a div around
# the nested label
config.item_wrapper_tag = :div
# CSS class to add for error notification helper.
config.error_notification_class = 'alert-box alert'
# The default wrapper to be used by the FormBuilder.
config.default_wrapper = :vertical_form
# Defines validation classes to the input_field. By default it's nil.
# config.input_field_valid_class = 'is-valid'
# config.input_field_error_class = 'is-invalid'
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/generators/simple_form/templates/config/initializers/simple_form_bootstrap.rb | lib/generators/simple_form/templates/config/initializers/simple_form_bootstrap.rb | # frozen_string_literal: true
# These defaults are defined and maintained by the community at
# https://github.com/heartcombo/simple_form-bootstrap
# Please submit feedback, changes and tests only there.
# Uncomment this and change the path if necessary to include your own
# components.
# See https://github.com/heartcombo/simple_form#custom-components
# to know more about custom components.
# Dir[Rails.root.join('lib/components/**/*.rb')].each { |f| require f }
# Use this setup block to configure all options available in SimpleForm.
SimpleForm.setup do |config|
# Default class for buttons
config.button_class = 'btn'
# Define the default class of the input wrapper of the boolean input.
config.boolean_label_class = 'form-check-label'
# How the label text should be generated altogether with the required text.
config.label_text = lambda { |label, required, explicit_label| "#{label} #{required}" }
# Define the way to render check boxes / radio buttons with labels.
config.boolean_style = :inline
# You can wrap each item in a collection of radio/check boxes with a tag
config.item_wrapper_tag = :div
# Defines if the default input wrapper class should be included in radio
# collection wrappers.
config.include_default_input_wrapper_class = false
# CSS class to add for error notification helper.
config.error_notification_class = 'alert alert-danger'
# Method used to tidy up errors. Specify any Rails Array method.
# :first lists the first message for each field.
# :to_sentence to list all errors for each field.
config.error_method = :to_sentence
# add validation classes to `input_field`
config.input_field_error_class = 'is-invalid'
config.input_field_valid_class = 'is-valid'
# vertical forms
#
# vertical default_wrapper
config.wrappers :vertical_form, class: 'mb-3' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :minlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label, class: 'form-label'
b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid'
b.use :full_error, wrap_with: { class: 'invalid-feedback' }
b.use :hint, wrap_with: { class: 'form-text' }
end
# vertical input for boolean
config.wrappers :vertical_boolean, tag: 'fieldset', class: 'mb-3' do |b|
b.use :html5
b.optional :readonly
b.wrapper :form_check_wrapper, class: 'form-check' do |bb|
bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
bb.use :label, class: 'form-check-label'
bb.use :full_error, wrap_with: { class: 'invalid-feedback' }
bb.use :hint, wrap_with: { class: 'form-text' }
end
end
# vertical input for radio buttons and check boxes
config.wrappers :vertical_collection, item_wrapper_class: 'form-check', item_label_class: 'form-check-label', tag: 'fieldset', class: 'mb-3' do |b|
b.use :html5
b.optional :readonly
b.wrapper :legend_tag, tag: 'legend', class: 'col-form-label pt-0' do |ba|
ba.use :label_text
end
b.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
b.use :full_error, wrap_with: { class: 'invalid-feedback d-block' }
b.use :hint, wrap_with: { class: 'form-text' }
end
# vertical input for inline radio buttons and check boxes
config.wrappers :vertical_collection_inline, item_wrapper_class: 'form-check form-check-inline', item_label_class: 'form-check-label', tag: 'fieldset', class: 'mb-3' do |b|
b.use :html5
b.optional :readonly
b.wrapper :legend_tag, tag: 'legend', class: 'col-form-label pt-0' do |ba|
ba.use :label_text
end
b.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
b.use :full_error, wrap_with: { class: 'invalid-feedback d-block' }
b.use :hint, wrap_with: { class: 'form-text' }
end
# vertical file input
config.wrappers :vertical_file, class: 'mb-3' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :minlength
b.optional :readonly
b.use :label, class: 'form-label'
b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid'
b.use :full_error, wrap_with: { class: 'invalid-feedback' }
b.use :hint, wrap_with: { class: 'form-text' }
end
# vertical select input
config.wrappers :vertical_select, class: 'mb-3' do |b|
b.use :html5
b.optional :readonly
b.use :label, class: 'form-label'
b.use :input, class: 'form-select', error_class: 'is-invalid', valid_class: 'is-valid'
b.use :full_error, wrap_with: { class: 'invalid-feedback' }
b.use :hint, wrap_with: { class: 'form-text' }
end
# vertical multi select
config.wrappers :vertical_multi_select, class: 'mb-3' do |b|
b.use :html5
b.optional :readonly
b.use :label, class: 'form-label'
b.wrapper class: 'd-flex flex-row justify-content-between align-items-center' do |ba|
ba.use :input, class: 'form-select mx-1', error_class: 'is-invalid', valid_class: 'is-valid'
end
b.use :full_error, wrap_with: { class: 'invalid-feedback d-block' }
b.use :hint, wrap_with: { class: 'form-text' }
end
# vertical range input
config.wrappers :vertical_range, class: 'mb-3' do |b|
b.use :html5
b.use :placeholder
b.optional :readonly
b.optional :step
b.use :label, class: 'form-label'
b.use :input, class: 'form-range', error_class: 'is-invalid', valid_class: 'is-valid'
b.use :full_error, wrap_with: { class: 'invalid-feedback' }
b.use :hint, wrap_with: { class: 'form-text' }
end
# horizontal forms
#
# horizontal default_wrapper
config.wrappers :horizontal_form, class: 'row mb-3' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :minlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label, class: 'col-sm-3 col-form-label'
b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba|
ba.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid'
ba.use :full_error, wrap_with: { class: 'invalid-feedback' }
ba.use :hint, wrap_with: { class: 'form-text' }
end
end
# horizontal input for boolean
config.wrappers :horizontal_boolean, class: 'row mb-3' do |b|
b.use :html5
b.optional :readonly
b.wrapper :grid_wrapper, class: 'col-sm-9 offset-sm-3' do |wr|
wr.wrapper :form_check_wrapper, class: 'form-check' do |bb|
bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
bb.use :label, class: 'form-check-label'
bb.use :full_error, wrap_with: { class: 'invalid-feedback' }
bb.use :hint, wrap_with: { class: 'form-text' }
end
end
end
# horizontal input for radio buttons and check boxes
config.wrappers :horizontal_collection, item_wrapper_class: 'form-check', item_label_class: 'form-check-label', class: 'row mb-3' do |b|
b.use :html5
b.optional :readonly
b.use :label, class: 'col-sm-3 col-form-label pt-0'
b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba|
ba.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
ba.use :full_error, wrap_with: { class: 'invalid-feedback d-block' }
ba.use :hint, wrap_with: { class: 'form-text' }
end
end
# horizontal input for inline radio buttons and check boxes
config.wrappers :horizontal_collection_inline, item_wrapper_class: 'form-check form-check-inline', item_label_class: 'form-check-label', class: 'row mb-3' do |b|
b.use :html5
b.optional :readonly
b.use :label, class: 'col-sm-3 col-form-label pt-0'
b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba|
ba.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
ba.use :full_error, wrap_with: { class: 'invalid-feedback d-block' }
ba.use :hint, wrap_with: { class: 'form-text' }
end
end
# horizontal file input
config.wrappers :horizontal_file, class: 'row mb-3' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :minlength
b.optional :readonly
b.use :label, class: 'col-sm-3 col-form-label'
b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba|
ba.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid'
ba.use :full_error, wrap_with: { class: 'invalid-feedback' }
ba.use :hint, wrap_with: { class: 'form-text' }
end
end
# horizontal select input
config.wrappers :horizontal_select, class: 'row mb-3' do |b|
b.use :html5
b.optional :readonly
b.use :label, class: 'col-sm-3 col-form-label'
b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba|
ba.use :input, class: 'form-select', error_class: 'is-invalid', valid_class: 'is-valid'
ba.use :full_error, wrap_with: { class: 'invalid-feedback' }
ba.use :hint, wrap_with: { class: 'form-text' }
end
end
# horizontal multi select
config.wrappers :horizontal_multi_select, class: 'row mb-3' do |b|
b.use :html5
b.optional :readonly
b.use :label, class: 'col-sm-3 col-form-label'
b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba|
ba.wrapper class: 'd-flex flex-row justify-content-between align-items-center' do |bb|
bb.use :input, class: 'form-select mx-1', error_class: 'is-invalid', valid_class: 'is-valid'
end
ba.use :full_error, wrap_with: { class: 'invalid-feedback d-block' }
ba.use :hint, wrap_with: { class: 'form-text' }
end
end
# horizontal range input
config.wrappers :horizontal_range, class: 'row mb-3' do |b|
b.use :html5
b.use :placeholder
b.optional :readonly
b.optional :step
b.use :label, class: 'col-sm-3 col-form-label pt-0'
b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba|
ba.use :input, class: 'form-range', error_class: 'is-invalid', valid_class: 'is-valid'
ba.use :full_error, wrap_with: { class: 'invalid-feedback' }
ba.use :hint, wrap_with: { class: 'form-text' }
end
end
# inline forms
#
# inline default_wrapper
config.wrappers :inline_form, class: 'col-12' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :minlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label, class: 'visually-hidden'
b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid'
b.use :error, wrap_with: { class: 'invalid-feedback' }
b.optional :hint, wrap_with: { class: 'form-text' }
end
# inline input for boolean
config.wrappers :inline_boolean, class: 'col-12' do |b|
b.use :html5
b.optional :readonly
b.wrapper :form_check_wrapper, class: 'form-check' do |bb|
bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
bb.use :label, class: 'form-check-label'
bb.use :error, wrap_with: { class: 'invalid-feedback' }
bb.optional :hint, wrap_with: { class: 'form-text' }
end
end
# bootstrap custom forms
#
# custom input switch for boolean
config.wrappers :custom_boolean_switch, class: 'mb-3' do |b|
b.use :html5
b.optional :readonly
b.wrapper :form_check_wrapper, tag: 'div', class: 'form-check form-switch' do |bb|
bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
bb.use :label, class: 'form-check-label'
bb.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' }
bb.use :hint, wrap_with: { class: 'form-text' }
end
end
# Input Group - custom component
# see example app and config at https://github.com/heartcombo/simple_form-bootstrap
config.wrappers :input_group, class: 'mb-3' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :minlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label, class: 'form-label'
b.wrapper :input_group_tag, class: 'input-group' do |ba|
ba.optional :prepend
ba.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid'
ba.optional :append
ba.use :full_error, wrap_with: { class: 'invalid-feedback' }
end
b.use :hint, wrap_with: { class: 'form-text' }
end
# Floating Labels form
#
# floating labels default_wrapper
config.wrappers :floating_labels_form, class: 'form-floating mb-3' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :minlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid'
b.use :label
b.use :full_error, wrap_with: { class: 'invalid-feedback' }
b.use :hint, wrap_with: { class: 'form-text' }
end
# custom multi select
config.wrappers :floating_labels_select, class: 'form-floating mb-3' do |b|
b.use :html5
b.optional :readonly
b.use :input, class: 'form-select', error_class: 'is-invalid', valid_class: 'is-valid'
b.use :label
b.use :full_error, wrap_with: { class: 'invalid-feedback' }
b.use :hint, wrap_with: { class: 'form-text' }
end
# The default wrapper to be used by the FormBuilder.
config.default_wrapper = :vertical_form
# Custom wrappers for input types. This should be a hash containing an input
# type as key and the wrapper that will be used for all inputs with specified type.
config.wrapper_mappings = {
boolean: :vertical_boolean,
check_boxes: :vertical_collection,
date: :vertical_multi_select,
datetime: :vertical_multi_select,
file: :vertical_file,
radio_buttons: :vertical_collection,
range: :vertical_range,
time: :vertical_multi_select,
select: :vertical_select
}
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/generators/simple_form/templates/config/initializers/simple_form.rb | lib/generators/simple_form/templates/config/initializers/simple_form.rb | # frozen_string_literal: true
#
# Uncomment this and change the path if necessary to include your own
# components.
# See https://github.com/heartcombo/simple_form#custom-components to know
# more about custom components.
# Dir[Rails.root.join('lib/components/**/*.rb')].each { |f| require f }
#
# Use this setup block to configure all options available in SimpleForm.
SimpleForm.setup do |config|
# Wrappers are used by the form builder to generate a
# complete input. You can remove any component from the
# wrapper, change the order or even add your own to the
# stack. The options given below are used to wrap the
# whole input.
config.wrappers :default, class: :input,
hint_class: :field_with_hint, error_class: :field_with_errors, valid_class: :field_without_errors do |b|
## Extensions enabled by default
# Any of these extensions can be disabled for a
# given input by passing: `f.input EXTENSION_NAME => false`.
# You can make any of these extensions optional by
# renaming `b.use` to `b.optional`.
# Determines whether to use HTML5 (:email, :url, ...)
# and required attributes
b.use :html5
# Calculates placeholders automatically from I18n
# You can also pass a string as f.input placeholder: "Placeholder"
b.use :placeholder
## Optional extensions
# They are disabled unless you pass `f.input EXTENSION_NAME => true`
# to the input. If so, they will retrieve the values from the model
# if any exists. If you want to enable any of those
# extensions by default, you can change `b.optional` to `b.use`.
# Calculates maxlength from length validations for string inputs
# and/or database column lengths
b.optional :maxlength
# Calculate minlength from length validations for string inputs
b.optional :minlength
# Calculates pattern from format validations for string inputs
b.optional :pattern
# Calculates min and max from length validations for numeric inputs
b.optional :min_max
# Calculates readonly automatically from readonly attributes
b.optional :readonly
## Inputs
# b.use :input, class: 'input', error_class: 'is-invalid', valid_class: 'is-valid'
b.use :label_input
b.use :hint, wrap_with: { tag: :span, class: :hint }
b.use :error, wrap_with: { tag: :span, class: :error }
## full_messages_for
# If you want to display the full error message for the attribute, you can
# use the component :full_error, like:
#
# b.use :full_error, wrap_with: { tag: :span, class: :error }
end
# The default wrapper to be used by the FormBuilder.
config.default_wrapper = :default
# Define the way to render check boxes / radio buttons with labels.
# Defaults to :nested for bootstrap config.
# inline: input + label
# nested: label > input
config.boolean_style = :nested
# Default class for buttons
config.button_class = 'btn'
# Method used to tidy up errors. Specify any Rails Array method.
# :first lists the first message for each field.
# Use :to_sentence to list all errors for each field.
# config.error_method = :first
# Default tag used for error notification helper.
config.error_notification_tag = :div
# CSS class to add for error notification helper.
config.error_notification_class = 'error_notification'
# Series of attempts to detect a default label method for collection.
# config.collection_label_methods = [ :to_label, :name, :title, :to_s ]
# Series of attempts to detect a default value method for collection.
# config.collection_value_methods = [ :id, :to_s ]
# You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
# config.collection_wrapper_tag = nil
# You can define the class to use on all collection wrappers. Defaulting to none.
# config.collection_wrapper_class = nil
# You can wrap each item in a collection of radio/check boxes with a tag,
# defaulting to :span.
# config.item_wrapper_tag = :span
# You can define a class to use in all item wrappers. Defaulting to none.
# config.item_wrapper_class = nil
# How the label text should be generated altogether with the required text.
# config.label_text = lambda { |label, required, explicit_label| "#{required} #{label}" }
# You can define the class to use on all labels. Default is nil.
# config.label_class = nil
# You can define the default class to be used on forms. Can be overridden
# with `html: { :class }`. Defaulting to none.
# config.default_form_class = nil
# You can define which elements should obtain additional classes
# config.generate_additional_classes_for = [:wrapper, :label, :input]
# Whether attributes are required by default (or not). Default is true.
# config.required_by_default = true
# Tell browsers whether to use the native HTML5 validations (novalidate form option).
# These validations are enabled in SimpleForm's internal config but disabled by default
# in this configuration, which is recommended due to some quirks from different browsers.
# To stop SimpleForm from generating the novalidate option, enabling the HTML5 validations,
# change this configuration to true.
config.browser_validations = false
# Custom mappings for input types. This should be a hash containing a regexp
# to match as key, and the input type that will be used when the field name
# matches the regexp as value.
# config.input_mappings = { /count/ => :integer }
# Custom wrappers for input types. This should be a hash containing an input
# type as key and the wrapper that will be used for all inputs with specified type.
# config.wrapper_mappings = { string: :prepend }
# Namespaces where SimpleForm should look for custom input classes that
# override default inputs.
# config.custom_inputs_namespaces << "CustomInputs"
# Default priority for time_zone inputs.
# config.time_zone_priority = nil
# Default priority for country inputs.
# config.country_priority = nil
# When false, do not use translations for labels.
# config.translate_labels = true
# Automatically discover new inputs in Rails' autoload path.
# config.inputs_discovery = true
# Cache SimpleForm inputs discovery
# config.cache_discovery = !Rails.env.development?
# Default class for inputs
# config.input_class = nil
# Define the default class of the input wrapper of the boolean input.
config.boolean_label_class = 'checkbox'
# Defines if the default input wrapper class should be included in radio
# collection wrappers.
# config.include_default_input_wrapper_class = true
# Defines which i18n scope will be used in Simple Form.
# config.i18n_scope = 'simple_form'
# Defines validation classes to the input_field. By default it's nil.
# config.input_field_valid_class = 'is-valid'
# config.input_field_error_class = 'is-invalid'
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/.github/workflows/github_actions_info.rb | .github/workflows/github_actions_info.rb | # logs repo/commit info
puts "ENV['GITHUB_WORKFLOW_REF'] #{ENV['GITHUB_WORKFLOW_REF']}\n" \
"ENV['GITHUB_WORKFLOW_SHA'] #{ENV['GITHUB_WORKFLOW_SHA']}\n" \
"ENV['GITHUB_REPOSITORY'] #{ENV['GITHUB_REPOSITORY']}\n" \
"ENV['GITHUB_REF_TYPE'] #{ENV['GITHUB_REF_TYPE']}\n" \
"ENV['GITHUB_REF'] #{ENV['GITHUB_REF']}\n" \
"ENV['GITHUB_REF_NAME'] #{ENV['GITHUB_REF_NAME']}"
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/benchmarks/local/long_tail_hey.rb | benchmarks/local/long_tail_hey.rb | # frozen_string_literal: true
require_relative 'bench_base'
require_relative 'puma_info'
require 'json'
module TestPuma
# This file is called from `long_tail_hey.sh`. It requires `hey`.
# See https://github.com/rakyll/hey.
#
# It starts a `Puma` server, then collects data from one or more runs of hey.
# It logs the hey data as each hey run is done, then summarizes the data.
#
# benchmarks/local/long_tail_hey.sh -t5:5 -R20 -d0.2 -C ./test/config/fork_worker.rb
#
# benchmarks/local/long_tail_hey.sh -w4 -t5:5 -R100 -d0.2
#
# See the file 'Testing - benchmark/local files' for sample output and information
# on arguments for the shell script.
#
# Examples:
#
# * `benchmarks/local/long_tail_hey.sh -w2 -t5:5 -s tcp6 -Y`<br/>
# 2 Puma workers, Puma threads 5:5, IPv6 http
#
# * `benchmarks/local/response_time_wrk.sh -t6:6 -s tcp -Y -b ac10,50,100`<br/>
# Puma single mode (0 workers), Puma threads 6:6, IPv4 http, six wrk runs,
# [array, chunk] * [10kb, 50kb, 100kb]
#
class LongTailHey < ResponseTimeBase
RACKUP_FILE = ENV.fetch('PUMA_RU_FILE', '')[/[^\/]+\z/]
HEY = ENV.fetch('HEY', 'hey')
CONNECTION_MULT = [6.0, 4.0, 3.0, 2.0, 1.5, 1.0, 0.5]
# CONNECTION_MULT = [2.0, 1.5, 1.0, 0.7, 0.5, 0.3]
CONNECTION_REQ = []
def run
time_start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
super
@errors = false
summaries = Hash.new { |h,k| h[k] = {} }
@stats_data = {}
@hey_data = {}
cpu_qty = ENV['HEY_CPUS']
hey_cpus = cpu_qty ? format('-cpus %2d ', cpu_qty) : ""
@ka = @no_keep_alive ? "-disable-keepalive" : ""
@worker_str = @workers.nil? ? ' ' : "-w#{@workers}"
@git_ref = %x[git branch --show-current].strip
@git_ref = %x[git log -1 --format=format:%H][0, 12] if @git_ref.empty?
@branch_line = "Branch: #{@git_ref}"
@puma_line = " Puma: #{@worker_str.ljust 4} " \
"-t#{@threads}:#{@threads} dly #{@dly_app} #{RACKUP_FILE}"
printed_hdr = false
CONNECTION_MULT.each do |mult|
workers = @workers || 1
connections = (mult * @threads * workers).round
CONNECTION_REQ << connections
hey_cmd = %Q[#{HEY} #{format '-c %3d -n %5d', connections, connections * @req_per_connection} #{hey_cpus}#{@ka} #{@wrk_bind_str}/sleep#{@dly_app}]
hey_cmd_len = hey_cmd.length/2 - 6
unless printed_hdr
STDOUT.syswrite "\n#{@puma_line.ljust 65}#{@branch_line}\nMult RPS 50% 99% " \
"#{'─' * hey_cmd_len} Hey Command #{'─' * hey_cmd_len}\n"
printed_hdr = true
end
@hey_data[connections] = run_hey_parse hey_cmd, mult, log: false
@puma_info.run 'gc'
@stats_data[connections] = parse_stats
end
run_summaries
rescue => e
STDOUT.syswrite "\n\nError #{e.class}\n#{e.message}\n#{e.backtrace}\n"
ensure
STDOUT.syswrite "\n"
@puma_info.run 'stop'
sleep 1
running_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) - time_start
STDOUT.syswrite format("\n%2d:%02d Total Time\n", (running_time/60).to_i, running_time % 60)
end
def run_summaries
STDOUT.syswrite "\n"
worker_div = 100/@workers.to_f
# Below are lines used in data logging
@hey_info_line = "Mult/Conn requests"
@hey_run_data = []
@hey_data.each do |k, data|
@hey_run_data[k] = "#{data[:mult]} #{k.to_s.rjust 3}"
end
begin
STDOUT.syswrite summary_hey_latency
STDOUT.syswrite summary_puma_stats
rescue => e
STDOUT.syswrite e.inspect
end
end
def summary_hey_latency
str = +"#{@puma_line}\n#{@branch_line}\n"
str << "#{@ka.ljust 28} ──────────────────── Hey Latency ──────────────────── Long Tail\n" \
"#{@hey_info_line} rps % 10% 25% 50% 75% 90% 95% 99% 100% 100% / 10%\n"
max_rps = @threads * (@workers || 1)/(100.0 * @dly_app)
@hey_data.each do |k, data|
str << format("#{@hey_run_data[k]} %6d %6.1f ", data[:requests], data[:rps].to_f/max_rps)
mult = data[:mult].to_f
mult = 1.0 if mult < 1.0
div = @dly_app * mult
data[:latency].each { |pc, time| str << format('%6.2f ', time/div) }
str << format('%8.2f', data[:latency][100]/data[:latency][10])
str << "\n"
end
str << "\n"
end
def summary_puma_stats
str = +"#{@puma_line}\n#{@branch_line}"
str_len = @branch_line.length
if (@workers || 0) > 1
# used for 'Worker Request Info' centering
# worker 2 3 4 5 6 7 8
wid_1 = [2, 3, 5, 8, 11, 14, 17]
ind_1 = wid_1[@workers - 2]
# used for '% deviation' centering
# worker 2 3 4 5 6 7 8
wid_2 = [3, 6, 9, 12, 15, 18, 21]
ind_2 = wid_2[@workers - 2]
spaces = str_len >= 49 ? ' ' : ' ' * (49 - str_len)
str << "#{spaces}#{'─' * ind_1} Worker Request Info #{'─' * ind_1}\n"
str << "#{@ka.ljust 21}─ Reactor ─ ─ Backlog ─" \
" Std #{' ' * ind_2}% deviation\n"
str << "#{@hey_info_line.ljust 19} Min Max Min Max" \
" Dev #{' ' * ind_2}from #{format '%5.2f', 100/@workers.to_f }%\n"
CONNECTION_REQ.each do |k|
backlog_max = []
reactor_max = []
requests = []
hsh = @stats_data[k]
hsh.each do |k, v|
backlog_max << (v[:backlog_max] || -1)
reactor_max << (v[:reactor_max] || -1)
requests << v[:requests]
end
if backlog_max[0] >= 0
str << format("#{@hey_run_data[k]} %6d %5d %5d %5d %5d",
requests.sum, reactor_max.min, reactor_max.max, backlog_max.min, backlog_max.max)
else # Puma 6 and earlier
str << format("#{@hey_run_data[k]} %6d %5s %5s %5s %5s", requests.sum,
'na', 'na', 'na', 'na')
end
# convert requests array into sorted percent array
div = k * @req_per_connection/@workers.to_f
percents = requests.sort.map { |r| percent = 100.0 * (r - div)/div }
# std dev calc
n = requests.length.to_f
sq_sum = 0
sum = 0
percents.each do |i|
sq_sum += i**2
sum += i
end
var = (sq_sum - sum**2/n)/n
percents_str = percents.map { |r| r.abs >= 100.0 ? format(' %5.0f', r) : format(' %5.1f', r) }.join
str << format(" %7.2f #{percents_str}\n", Math.sqrt(var))
end
else
str << "\n#{@ka.ljust 21}─ Reactor ─ ─ Backlog ─\n"
str << "#{@hey_info_line.ljust 19} Min/Max Min/Max\n"
one_worker = @workers == 1
CONNECTION_REQ.each do |k|
hsh = one_worker ? @stats_data[k].values[0] : @stats_data[k]
if hsh[:reactor_max]
str << format("#{@hey_run_data[k]} %6d %3d %3d\n",
hsh[:requests], hsh[:reactor_max], hsh[:backlog_max])
else
str << format("#{@hey_run_data[k]} %6d %3s %3s\n",
hsh[:requests], 'na', 'na')
end
end
end
str
end # summary_puma_stats
end # LongTailHey
end # TestPuma
TestPuma::LongTailHey.new.run
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/benchmarks/local/bench_base.rb | benchmarks/local/bench_base.rb | # frozen_string_literal: true
require 'optparse'
module TestPuma
HOST4 = ENV.fetch('PUMA_TEST_HOST4', '127.0.0.1')
HOST6 = ENV.fetch('PUMA_TEST_HOST6', '::1')
PORT = ENV.fetch('PUMA_TEST_PORT', 40001).to_i
# Array of response body sizes. If specified, set by ENV['PUMA_TEST_SIZES']
#
SIZES = if (t = ENV['PUMA_TEST_SIZES'])
t.split(',').map(&:to_i).freeze
else
[1, 10, 100, 256, 512, 1024, 2048].freeze
end
TYPES = [[:a, 'array'].freeze, [:c, 'chunk'].freeze,
[:s, 'string'].freeze, [:i, 'io'].freeze].freeze
# Creates files used by 'i' (File/IO) responses. Placed in
# "#{Dir.tmpdir}/.puma_response_body_io"
# @param sizes [Array <Integer>] Array of sizes
#
def self.create_io_files(sizes = SIZES)
require 'tmpdir'
tmp_folder = "#{Dir.tmpdir}/.puma_response_body_io"
Dir.mkdir(tmp_folder) unless Dir.exist? tmp_folder
fn_format = "#{tmp_folder}/body_io_%04d.txt"
str = ("── Puma Hello World! ── " * 31) + "── Puma Hello World! ──\n" # 1 KB
sizes.each do |len|
suf = format "%04d", len
fn = format fn_format, len
unless File.exist? fn
body = "Hello World\n#{str}".byteslice(0,1023) + "\n" + (str * (len-1))
File.write fn, body
end
end
end
# Base class for generating client request streams
#
class BenchBase
# We're running under GitHub Actions
IS_GHA = ENV['GITHUB_ACTIONS'] == 'true'
WRK_PERCENTILE = [0.50, 0.75, 0.9, 0.99, 1.0].freeze
HDR_BODY_CONF = "Body-Conf: "
# extracts 'type' string from `-b` argument
TYPES_RE = /\A[acis]+/.freeze
# extracts 'size' string from `-b` argument
SIZES_RE = /\d[\d,]*\z/.freeze
def initialize
# wait for server to boot
sleep (RUBY_ENGINE == 'ruby' ? 2.0 : 8.0)
@thread_loops = nil
@clients_per_thread = nil
@req_per_client = nil
@body_sizes = SIZES
@body_types = TYPES
@dly_app = nil
@bind_type = :tcp
@worker_req_ttl = {}
@pids = {}
@ios_to_close = []
setup_options
unless File.exist? @state_file
puts "Can't find state file '#{@state_file}'"
exit 1
end
mstr_pid = File.binread(@state_file)[/^pid: +(\d+)/, 1].to_i
begin
Process.kill 0, mstr_pid
rescue Errno::ESRCH
puts 'Puma server stopped?'
exit 1
rescue Errno::EPERM
end
case @bind_type
when :ssl, :ssl4, :tcp, :tcp4
@bind_host = HOST4
@bind_port = PORT
when :ssl6, :tcp6
@bind_host = HOST6
@bind_port = PORT
when :unix
@bind_path = 'tmp/benchmark_skt.unix'
when :aunix
@bind_path = '@benchmark_skt.aunix'
else
exit 1
end
end
def setup_options
# STDOUT.syswrite "\n\n#{ARGV}\n"
OptionParser.new do |o|
o.on "-T", "--stream-threads THREADS", OptionParser::DecimalInteger, "request_stream: loops/threads" do |arg|
@stream_threads = arg.to_i
end
o.on "-c", "--wrk-connections CONNECTIONS", OptionParser::DecimalInteger, "request_stream: clients_per_thread" do |arg|
@connections = arg.to_i
end
o.on "-R", "--requests REQUESTS", OptionParser::DecimalInteger, "request_stream: requests per socket" do |arg|
@req_per_connection = arg.to_i
end
o.on "-D", "--duration DURATION", OptionParser::DecimalInteger, "wrk/stream: duration" do |arg|
@duration = arg.to_i
end
o.on "-d", "--dly_app DELAYAPP", Float, "CI RackUp: app response delay" do |arg|
@dly_app = arg.to_f
end
o.on "-s", "--socket SOCKETTYPE", String, "Bind type: tcp, ssl, tcp6, ssl6, unix, aunix" do |arg|
@bind_type = arg.to_sym
end
o.on "-S", "--state PUMA_STATEFILE", String, "Puma Server: state file" do |arg|
@state_file = arg
end
o.on "-t", "--threads PUMA_THREADS", String, "Puma Server: threads" do |arg|
@threads = arg.match?(/\d+:\d+/) ? arg[/\d+\z/].to_i : arg.to_i
end
o.on "-w", "--workers PUMA_WORKERS", OptionParser::DecimalInteger, "Puma Server: workers" do |arg|
@workers = arg.to_i
end
o.on "-W", "--wrk_bind WRK_STR", String, "wrk: bind string" do |arg|
@wrk_bind_str = arg
end
o.on "-k", "--disable-keepalive", "hey no keep alive" do
@no_keep_alive = true
end
o.on("-h", "--help", "Prints this help") do
puts o
exit
end
end.parse! ARGV
end
def close_clients
closed = 0
@ios_to_close.each do |socket|
if socket && socket.to_io.is_a?(IO) && !socket.closed?
begin
if @bind_type == :ssl
socket.sysclose
else
socket.close
end
closed += 1
rescue Errno::EBADF
end
end
end
puts "Closed #{closed} sockets" unless closed.zero?
end
# Runs hey and returns data from its output.
# @param cmd [String] The hey command string, with arguments
# @return [Hash] The hey data
#
def run_hey_parse(cmd, mult, log: false)
STDOUT.syswrite format('%4.2f', mult)
hey_output = %x[#{cmd}].strip.gsub(' secs', '')
STDOUT.syswrite "\n\n#{hey_output}\n\n" if log
job = {}
status_code_dist = hey_output[/^Status code distribution:\s+(.+?)\z/m, 1].strip.gsub(/^\s+\[/, '[')
job[:requests] = status_code_dist[/\[2\d\d\][\t ]+(\d+)[\t ]+responses/, 1].to_i
if status_code_dist.include? "\n"
job[:error] = status_code_dist
STDOUT.syswrite "\nERRORS:\n#{status_code_dist}\n"
end
job[:mult] = format '%4.2f', mult
job[:rps] = hey_output[/^\s+Requests\/sec\:\s+([\d.]+)/, 1]
latency = hey_output[/^Latency distribution:\n(.+?)\n\n/m, 1].gsub(/^ +/, '').gsub('in ', '').gsub(' secs', '')
if latency
temp = job[:latency] = {}
latency.lines.each do |l|
per_cent = l[/\A\d+/].to_i
temp[per_cent] = per_cent.zero? ? 0.0 : l.rstrip[/[\d.]+\z/].to_f
end
temp[100] = hey_output[/^\s+Slowest\:\s+([\d.]+)/, 1].to_f
end
STDOUT.syswrite format(" %6d %7.4f %7.4f %s\n", job[:rps].to_i, job[:latency][50], job[:latency][99], cmd) unless log
job
end
# Runs wrk and returns data from its output.
# @param cmd [String] The wrk command string, with arguments
# @return [Hash] The wrk data
#
def run_wrk_parse(cmd, log: false)
STDOUT.syswrite cmd.ljust 55
if @dly_app
cmd.sub! ' -H ', " -H 'Dly: #{@dly_app.round 4}' -H "
end
wrk_output = %x[#{cmd}]
if log
puts '', wrk_output, ''
end
wrk_data = "#{wrk_output[/\A.+ connections/m]}\n#{wrk_output[/ Thread Stats.+\z/m]}"
ary = wrk_data[/^ +\d+ +requests.+/].strip.split ' '
fmt = " | %6s %s %s %7s %8s %s\n"
STDOUT.syswrite format(fmt, *ary)
hsh = {}
rps = wrk_data[/^Requests\/sec: +([\d.]+)/, 1].to_f
requests = wrk_data[/^ +(\d+) +requests/, 1].to_i
transfer = wrk_data[/^Transfer\/sec: +([\d.]+)/, 1].to_f
transfer_unit = wrk_data[/^Transfer\/sec: +[\d.]+(GB|KB|MB)/, 1]
transfer_mult = mult_for_unit transfer_unit
read = wrk_data[/ +([\d.]+)(GB|KB|MB) +read$/, 1].to_f
read_unit = wrk_data[/ +[\d.]+(GB|KB|MB) +read$/, 1]
read_mult = mult_for_unit read_unit
resp_transfer = (transfer * transfer_mult)/rps
resp_read = (read * read_mult)/requests.to_f
mult = transfer/read
hsh[:resp_size] = ((resp_transfer * mult + resp_read)/(mult + 1)).round
hsh[:resp_size] = hsh[:resp_size] - 1770 - hsh[:resp_size].to_s.length
hsh[:rps] = rps.round
hsh[:requests] = requests
if (t = wrk_data[/^ +Socket errors: +(.+)/, 1])
hsh[:errors] = t
end
read = wrk_data[/ +([\d.]+)(GB|KB|MB) +read$/, 1].to_f
unit = wrk_data[/ +[\d.]+(GB|KB|MB) +read$/, 1]
mult = mult_for_unit unit
hsh[:read] = (mult * read).round
if hsh[:errors]
t = hsh[:errors]
hsh[:errors] = t.sub('connect ', 'c').sub('read ', 'r')
.sub('write ', 'w').sub('timeout ', 't')
end
t_re = ' +([\d.ums]+)'
latency =
wrk_data.match(/^ +50%#{t_re}\s+75%#{t_re}\s+90%#{t_re}\s+99%#{t_re}/).captures
# add up max time
latency.push wrk_data[/^ +Latency.+/].split(' ')[-2]
hsh[:times_summary] = WRK_PERCENTILE.zip(latency.map do |t|
if t.end_with?('ms')
t.to_f
elsif t.end_with?('us')
t.to_f/1000
elsif t.end_with?('s')
t.to_f * 1000
else
0
end
end).to_h
hsh
end
def mult_for_unit(unit)
case unit
when 'KB' then 1_024
when 'MB' then 1_024**2
when 'GB' then 1_024**3
end
end
# Outputs info about the run. Example output:
#
# benchmarks/local/response_time_wrk.sh -w2 -t5:5 -s tcp6
# Server cluster mode -w2 -t5:5, bind: tcp6
# Puma repo branch 00-response-refactor
# ruby 3.2.0dev (2022-06-11T12:26:03Z master 28e27ee76e) +YJIT [x86_64-linux]
#
def env_log
puts "#{ENV['PUMA_BENCH_CMD']} #{ENV['PUMA_BENCH_ARGS']}"
puts @workers ?
"Server cluster mode -w#{@workers} -t#{@threads}, bind: #{@bind_type}" :
"Server single mode -t#{@threads}, bind: #{@bind_type}"
branch = %x[git branch][/^\* (.*)/, 1]
if branch
puts "Puma repo branch #{branch.strip}", RUBY_DESCRIPTION
else
const = File.read File.expand_path('../../lib/puma/const.rb', __dir__)
puma_version = const[/^ +PUMA_VERSION[^'"]+['"]([^\s'"]+)/, 1]
puts "Puma version #{puma_version}", RUBY_DESCRIPTION
end
end
# Parses data returned by `PumaInfo.run 'stats'`
# @return [Hash] The data from Puma stats
#
def parse_stats
sleep 5.5
obj = @puma_info.run 'stats'
stats = {}
if (worker_status = obj[:worker_status])
worker_status.each do |w|
pid = w[:pid]
@worker_req_ttl[pid] ||= 0
req_cnt = w[:last_status][:requests_count]
id = format 'worker-%01d-%02d', w[:phase], w[:index]
hsh = {
pid: pid,
requests: req_cnt - @worker_req_ttl[pid],
backlog: w[:last_status][:backlog],
backlog_max: w[:last_status][:backlog_max],
reactor_max: w[:last_status][:reactor_max]
}
@pids[pid] = id
@worker_req_ttl[pid] = req_cnt
stats[id] = hsh
end
else
@req_ttl ||= 0
req_cnt = obj[:requests_count]
hsh = {
pid: 0,
requests: req_cnt - @req_ttl,
backlog: obj[:backlog],
backlog_max: obj[:backlog_max],
reactor_max: obj[:reactor_max]
}
@req_ttl = req_cnt
stats = hsh
end
stats
end
# Runs gc in the server, then parses data from
# `smem -c 'pid rss pss uss command'`
# @return [Hash] The data from smem
#
def parse_smem
@puma_info.run 'gc'
sleep 1
hsh_smem = Hash.new []
pids = @pids.keys
smem_info = %x[smem -c 'pid rss pss uss command']
smem_info.lines.each do |l|
ary = l.strip.split ' ', 5
if pids.include? ary[0].to_i
hsh_smem[@pids[ary[0].to_i]] = {
pid: ary[0].to_i,
rss: ary[1].to_i,
pss: ary[2].to_i,
uss: ary[3].to_i
}
end
end
hsh_smem.sort.to_h
end
end
class ResponseTimeBase < BenchBase
def run
@puma_info = PumaInfo.new ['-S', @state_file]
end
# Prints summarized data. Example:
# ```
# Body ────────── req/sec ────────── ─────── req 50% times ───────
# KB array chunk string io array chunk string io
# 1 13760 13492 13817 9610 0.744 0.759 0.740 1.160
# 10 13536 13077 13492 9269 0.759 0.785 0.760 1.190
# ```
#
# @param summaries [Hash] generated in subclasses
#
def overall_summary(summaries)
names = +''
@body_types.each { |_, t_desc| names << t_desc.rjust(8) }
puts "\nBody ────────── req/sec ────────── ─────── req 50% times ───────" \
"\n KB #{names.ljust 32}#{names}"
len = @body_types.length
digits = [4 - Math.log10(@max_050_time).to_i, 3].min
fmt_rps = ('%6d ' * len).strip
fmt_times = (digits < 0 ? " %6d" : " %6.#{digits}f") * len
@body_sizes.each do |size|
line = format '%-5d ', size
resp = ''
line << format(fmt_rps , *@body_types.map { |_, t_desc| summaries[size][t_desc][:rps] }).ljust(30)
line << format(fmt_times, *@body_types.map { |_, t_desc| summaries[size][t_desc][:times_summary][0.5] })
puts line
end
puts '─' * 69
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/benchmarks/local/puma_info.rb | benchmarks/local/puma_info.rb | # frozen_string_literal: true
require 'optparse'
require_relative '../../lib/puma/state_file'
require_relative '../../lib/puma/const'
require_relative '../../lib/puma/detect'
require_relative '../../lib/puma/configuration'
require 'uri'
require 'socket'
require 'json'
module TestPuma
# Similar to puma_ctl.rb, but returns objects. Command list is minimal.
#
class PumaInfo
# @version 5.0.0
PRINTABLE_COMMANDS = %w{gc-stats stats stop thread-backtraces}.freeze
COMMANDS = (PRINTABLE_COMMANDS + %w{gc}).freeze
attr_reader :master_pid
def initialize(argv, stdout=STDOUT, stderr=STDERR)
@state = nil
@quiet = false
@pidfile = nil
@pid = nil
@control_url = nil
@control_auth_token = nil
@config_file = nil
@command = nil
@environment = ENV['RACK_ENV'] || ENV['RAILS_ENV']
@argv = argv
@stdout = stdout
@stderr = stderr
@cli_options = {}
opts = OptionParser.new do |o|
o.banner = "Usage: pumactl (-p PID | -P pidfile | -S status_file | -C url -T token | -F config.rb) (#{PRINTABLE_COMMANDS.join("|")})"
o.on "-S", "--state PATH", "Where the state file to use is" do |arg|
@state = arg
end
o.on "-Q", "--quiet", "Not display messages" do |arg|
@quiet = true
end
o.on "-C", "--control-url URL", "The bind url to use for the control server" do |arg|
@control_url = arg
end
o.on "-T", "--control-token TOKEN", "The token to use as authentication for the control server" do |arg|
@control_auth_token = arg
end
o.on "-F", "--config-file PATH", "Puma config script" do |arg|
@config_file = arg
end
o.on "-e", "--environment ENVIRONMENT",
"The environment to run the Rack app on (default development)" do |arg|
@environment = arg
end
o.on_tail("-H", "--help", "Show this message") do
@stdout.puts o
exit
end
o.on_tail("-V", "--version", "Show version") do
@stdout.puts Const::PUMA_VERSION
exit
end
end
opts.order!(argv) { |a| opts.terminate a }
opts.parse!
unless @config_file == '-'
environment = @environment || 'development'
if @config_file.nil?
@config_file = %W(config/puma/#{environment}.rb config/puma.rb).find do |f|
File.exist?(f)
end
end
if @config_file
config = Puma::Configuration.new({ config_files: [@config_file] }, {})
config.clamp
@state ||= config.options[:state]
@control_url ||= config.options[:control_url]
@control_auth_token ||= config.options[:control_auth_token]
@pidfile ||= config.options[:pidfile]
end
end
@master_pid = File.binread(@state)[/^pid: +(\d+)/, 1].to_i
rescue => e
@stdout.puts e.message
exit 1
end
def message(msg)
@stdout.puts msg unless @quiet
end
def prepare_configuration
if @state
unless File.exist? @state
raise "State file not found: #{@state}"
end
sf = Puma::StateFile.new
sf.load @state
@control_url = sf.control_url
@control_auth_token = sf.control_auth_token
@pid = sf.pid
end
end
def send_request
uri = URI.parse @control_url
# create server object by scheme
server =
case uri.scheme
when 'ssl'
require 'openssl'
OpenSSL::SSL::SSLSocket.new(
TCPSocket.new(uri.host, uri.port),
OpenSSL::SSL::SSLContext.new)
.tap { |ssl| ssl.sync_close = true } # default is false
.tap(&:connect)
when 'tcp'
TCPSocket.new uri.host, uri.port
when 'unix'
# check for abstract UNIXSocket
UNIXSocket.new(@control_url.start_with?('unix://@') ?
"\0#{uri.host}#{uri.path}" : "#{uri.host}#{uri.path}")
else
raise "Invalid scheme: #{uri.scheme}"
end
url = "/#{@command}"
if @control_auth_token
url = url + "?token=#{@control_auth_token}"
end
server.syswrite "GET #{url} HTTP/1.0\r\n\r\n"
unless data = server.read
raise 'Server closed connection before responding'
end
response = data.split("\r\n")
if response.empty?
raise "Server sent empty response"
end
@http, @code, @message = response.first.split(' ',3)
if @code == '403'
raise 'Unauthorized access to server (wrong auth token)'
elsif @code == '404'
raise "Command error: #{response.last}"
elsif @code == '500' && @command == 'stop-sigterm'
# expected with stop-sigterm
elsif @code != '200'
raise "Bad response from server: #{@code}"
end
return unless PRINTABLE_COMMANDS.include? @command
JSON.parse response.last, {symbolize_names: true}
ensure
if server
if uri.scheme == 'ssl'
server.sysclose
else
server.close unless server.closed?
end
end
end
def run(cmd)
return unless COMMANDS.include?(cmd)
@command = cmd
prepare_configuration
send_request
rescue => e
message e.message
exit 1
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/benchmarks/local/response_time_wrk.rb | benchmarks/local/response_time_wrk.rb | # frozen_string_literal: true
require_relative 'bench_base'
require_relative 'puma_info'
module TestPuma
# This file is called from `response_time_wrk.sh`. It requires `wrk`.
# We suggest using https://github.com/ioquatix/wrk
#
# It starts a `Puma` server, then collects data from one or more runs of wrk.
# It logs the wrk data as each wrk runs is done, then summarizes
# the data in two tables.
#
# The default runs a matrix of the following, and takes a bit over 5 minutes,
# with 28 (4x7) wrk runs:
#
# bodies - array, chunk, string, io<br/>
#
# sizes - 1k, 10k, 100k, 256k, 512k, 1024k, 2048k
#
# See the file 'Testing - benchmark/local files' for sample output and information
# on arguments for the shell script.
#
# Examples:
#
# * `benchmarks/local/response_time_wrk.sh -w2 -t5:5 -s tcp6 -Y`<br/>
# 2 Puma workers, Puma threads 5:5, IPv6 http, 28 wrk runs with matrix above
#
# * `benchmarks/local/response_time_wrk.sh -t6:6 -s tcp -Y -b ac10,50,100`<br/>
# Puma single mode (0 workers), Puma threads 6:6, IPv4 http, six wrk runs,
# [array, chunk] * [10kb, 50kb, 100kb]
#
class ResponseTimeWrk < ResponseTimeBase
WRK = ENV.fetch('WRK', 'wrk')
def run
time_start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
super
# default values
@duration ||= 10
max_threads = (@threads[/\d+\z/] || 5).to_i
@stream_threads ||= (0.8 * (@workers || 1) * max_threads).to_i
connections = @stream_threads * (@connections || 2)
warm_up
@max_100_time = 0
@max_050_time = 0
@errors = false
summaries = Hash.new { |h,k| h[k] = {} }
@single_size = @body_sizes.length == 1
@single_type = @body_types.length == 1
@body_sizes.each do |size|
@body_types.each do |pre, desc|
header = @single_size ? "-H '#{HDR_BODY_CONF}#{pre}#{size}'" :
"-H '#{HDR_BODY_CONF}#{pre}#{size}'".ljust(21)
# warmup?
if pre == :i
wrk_cmd = %Q[#{WRK} -t#{@stream_threads} -c#{connections} -d1s --latency #{header} #{@wrk_bind_str}]
%x[#{wrk_cmd}]
end
wrk_cmd = %Q[#{WRK} -t#{@stream_threads} -c#{connections} -d#{@duration}s --latency #{header} #{@wrk_bind_str}]
hsh = run_wrk_parse wrk_cmd
@errors ||= hsh.key? :errors
times = hsh[:times_summary]
@max_100_time = times[1.0] if times[1.0] > @max_100_time
@max_050_time = times[0.5] if times[0.5] > @max_050_time
summaries[size][desc] = hsh
end
sleep 0.5
@puma_info.run 'gc'
sleep 2.0
end
run_summaries summaries
if @single_size || @single_type
puts ''
else
overall_summary(summaries) unless @single_size || @single_type
end
puts "wrk -t#{@stream_threads} -c#{connections} -d#{@duration}s"
env_log
rescue => e
puts e.class, e.message, e.backtrace
ensure
puts ''
@puma_info.run 'stop'
sleep 2
running_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) - time_start
puts format("\n%2d:%d Total Time", (running_time/60).to_i, running_time % 60)
end
# Prints parsed data of each wrk run. Similar to:
# ```
# Type req/sec 50% 75% 90% 99% 100% Resp Size
# ───────────────────────────────────────────────────────────────── 1kB
# array 13760 0.74 2.51 5.22 7.76 11.18 2797
# ```
#
# @param summaries [Hash]
#
def run_summaries(summaries)
digits = [4 - Math.log10(@max_100_time).to_i, 3].min
fmt_vals = +'%-6s %6d'
fmt_vals << (digits < 0 ? " %6d" : " %6.#{digits}f")*5
fmt_vals << ' %8d'
label = @single_type ? 'Size' : 'Type'
if @errors
puts "\n#{label} req/sec 50% 75% 90% 99% 100% Resp Size Errors"
desc_width = 83
else
puts "\n#{label} req/sec 50% 75% 90% 99% 100% Resp Size"
desc_width = 65
end
puts format("#{'─' * desc_width} %s", @body_types[0][1]) if @single_type
@body_sizes.each do |size|
puts format("#{'─' * desc_width}%5dkB", size) unless @single_type
@body_types.each do |_, t_desc|
hsh = summaries[size][t_desc]
times = hsh[:times_summary].values
desc = @single_type ? size : t_desc
# puts format(fmt_vals, desc, hsh[:rps], *times, hsh[:read]/hsh[:requests])
puts format(fmt_vals, desc, hsh[:rps], *times, hsh[:resp_size])
end
end
end
# Checks if any body files need to be created, reads all the body files,
# then runs a quick 'wrk warmup' command for each body type
#
def warm_up
puts "\nwarm-up"
if @body_types.map(&:first).include? :i
TestPuma.create_io_files @body_sizes
# get size files cached
if @body_types.include? :i
2.times do
@body_sizes.each do |size|
fn = format "#{Dir.tmpdir}/.puma_response_body_io/body_io_%04d.txt", size
t = File.read fn, mode: 'rb'
end
end
end
end
size = @body_sizes.length == 1 ? @body_sizes.first : 10
@body_types.each do |pre, _|
header = "-H '#{HDR_BODY_CONF}#{pre}#{size}'".ljust(21)
warm_up_cmd = %Q[#{WRK} -t2 -c4 -d1s --latency #{header} #{@wrk_bind_str}]
run_wrk_parse warm_up_cmd
end
puts ''
end
# Experimental - try to see how busy a CI system is.
def ci_test_rps
host = ENV['HOST']
port = ENV['PORT'].to_i
str = 'a' * 65_500
server = TCPServer.new host, port
svr_th = Thread.new do
loop do
begin
Thread.new(server.accept) do |client|
client.sysread 65_536
client.syswrite str
client.close
end
rescue => e
break
end
end
end
threads = []
t_st = Process.clock_gettime(Process::CLOCK_MONOTONIC)
100.times do
threads << Thread.new do
100.times {
s = TCPSocket.new host, port
s.syswrite str
s.sysread 65_536
s = nil
}
end
end
threads.each(&:join)
loops_time = (1_000*(Process.clock_gettime(Process::CLOCK_MONOTONIC) - t_st)).to_i
threads.clear
threads = nil
server.close
svr_th.join
req_limit =
if loops_time > 3_050 then 13_000
elsif loops_time > 2_900 then 13_500
elsif loops_time > 2_500 then 14_000
elsif loops_time > 2_200 then 18_000
elsif loops_time > 2_100 then 19_000
elsif loops_time > 1_900 then 20_000
elsif loops_time > 1_800 then 21_000
elsif loops_time > 1_600 then 22_500
else 23_000
end
[req_limit, loops_time]
end
def puts(*ary)
ary.each { |s| STDOUT.syswrite "#{s}\n" }
end
end
end
TestPuma::ResponseTimeWrk.new.run
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/benchmarks/local/sleep_fibonacci_test.rb | benchmarks/local/sleep_fibonacci_test.rb | # frozen_string_literal: true
=begin
change to benchmarks/local folder
ruby sleep_fibonacci_test.rb s
ruby sleep_fibonacci_test.rb m
ruby sleep_fibonacci_test.rb l
ruby sleep_fibonacci_test.rb a
ruby sleep_fibonacci_test.rb 0.001,0.005,0.01,0.02,0.04
=end
module SleepFibonacciTest
class << self
TIME_RE = / ([\d.]+) Time/
LOOPS_RE = / (\d+) Loops\n\z/
CPU_RE = / ([\d.]+)% CPU/
FORMAT_DATA = "%5.0f %6.2f %6.2f %6.2f %3d %4.1f%%\n"
LEGEND = " Delay ─── Min ──── Aver ─── Max ─── Loops ─── CPU ─── all times mS ──\n"
CLK_MONO = Process::CLOCK_MONOTONIC
def run(blk)
@app = blk
end
def test_single(delay)
sum_time = 0
sum_loops = 0
sum_cpu = 0
min = 1_000_000
max = 0
10.times do
env = {'REQUEST_PATH' => "/sleep#{delay}"}
t_st = Process.clock_gettime CLK_MONO
info = @app.call(env)[2].first
time = Process.clock_gettime(CLK_MONO) - t_st
# STDOUT.syswrite " #{info}"
sum_loops += info[LOOPS_RE ,1].to_i
sum_time += time
sum_cpu += info[CPU_RE ,1].to_f
min = time if time < min
max = time if time > max
end
STDOUT.syswrite format(FORMAT_DATA,
1000.0 * delay,
1000.0 * min,
100.0 * sum_time,
1000.0 * max,
sum_loops/10.0,
sum_cpu/10.0
)
end
def test
instance_eval File.read("#{__dir__}/../../test/rackup/sleep_fibonacci.ru")
# Small 0.001 - 0.009
# Medium 0.01 - 0.09
# Large 0.1 - 0.9
# All
type = ARGV[0] || 'm' # run all
if type.match?(/[AaSsMmLl]/)
STDOUT.syswrite LEGEND
9.times { |i| test_single(0.001 * (i+1)) } if type.match?(/[SsAa]/)
STDOUT.syswrite LEGEND if type.match?(/[Aa]/)
9.times { |i| test_single(0.01 * (i+1)) } if type.match?(/[MmAa]/)
STDOUT.syswrite LEGEND if type.match?(/[Aa]/)
9.times { |i| test_single(0.1 * (i+1)) } if type.match?(/[LlAa]/)
else
sleep_ary = type.split(',').map(&:to_f)
sleep_ary.each do |slp|
env = {'REQUEST_PATH' => "/sleep#{slp}"}
puts @app.call(env)[2].first
end
end
end
end
end
SleepFibonacciTest.test
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/benchmarks/local/sinatra/puma.rb | benchmarks/local/sinatra/puma.rb | silence_single_worker_warning
workers 1
before_fork do
require "puma_worker_killer"
PumaWorkerKiller.config do |config|
config.ram = 1024 # mb
config.frequency = 0.3 # seconds
config.reaper_status_logs = true # Log memory: PumaWorkerKiller: Consuming 54.34765625 mb with master and 1 workers.
end
PumaWorkerKiller.start
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/tools/trickletest.rb | tools/trickletest.rb | require 'socket'
require 'stringio'
def do_test(st, chunk)
s = TCPSocket.new('127.0.0.1',ARGV[0].to_i);
req = StringIO.new(st)
nout = 0
randstop = rand(st.length / 10)
STDERR.puts "stopping after: #{randstop}"
begin
while data = req.read(chunk)
nout += s.write(data)
s.flush
sleep 0.1
if nout > randstop
STDERR.puts "BANG! after #{nout} bytes."
break
end
end
rescue Object => e
STDERR.puts "ERROR: #{e}"
ensure
s.close
end
end
content = "-" * (1024 * 240)
st = "GET / HTTP/1.1\r\nHost: www.zedshaw.com\r\nContent-Type: text/plain\r\nContent-Length: #{content.length}\r\n\r\n#{content}"
puts "length: #{content.length}"
threads = []
ARGV[1].to_i.times do
t = Thread.new do
size = 100
puts ">>>> #{size} sized chunks"
do_test(st, size)
end
threads << t
end
threads.each {|t| t.join}
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_fiber_storage_application.rb | test/test_fiber_storage_application.rb | # frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2023, by Samuel Williams.
require_relative "helper"
require "puma/server"
class FiberStorageApplication
def call(env)
count = (Fiber[:request_count] ||= 0)
Fiber[:request_count] += 1
[200, {"Content-Type" => "text/plain"}, [count.to_s]]
end
end
class FiberStorageApplicationTest < PumaTest
parallelize_me!
def setup
skip "Fiber Storage is not supported on this Ruby" unless Fiber.respond_to?(:[])
@tester = FiberStorageApplication.new
@server = Puma::Server.new @tester, nil, {log_writer: Puma::LogWriter.strings, fiber_per_request: true}
@port = (@server.add_tcp_listener "127.0.0.1", 0).addr[1]
@tcp = "http://127.0.0.1:#{@port}"
@server.run
end
def teardown
@server.stop(true)
end
def test_empty_storage
skip_if :oldwindows
response = hit(["#{@tcp}/test"] * 3)
assert_equal ["0", "0", "0"], response
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_app_status.rb | test/test_app_status.rb | # frozen_string_literal: true
require_relative "helper"
require "puma/app/status"
require "rack"
class TestAppStatus < PumaTest
class FakeServer
def initialize
@status = :running
end
attr_reader :status
def stop
@status = :stop
end
def halt
@status = :halt
end
def stats
{}
end
end
def setup
@server = FakeServer.new
@app = Puma::App::Status.new(@server)
end
def lint(uri)
app = Rack::Lint.new @app
mock_env = Rack::MockRequest.env_for uri
app.call mock_env
end
def test_bad_token
@app.instance_variable_set(:@auth_token, "abcdef")
status, _, _ = lint('/whatever')
assert_equal 403, status
end
def test_good_token
@app.instance_variable_set(:@auth_token, "abcdef")
status, _, _ = lint('/whatever?token=abcdef')
assert_equal 404, status
end
def test_multiple_params
@app.instance_variable_set(:@auth_token, "abcdef")
status, _, _ = lint('/whatever?foo=bar&token=abcdef')
assert_equal 404, status
end
def test_unsupported
status, _, _ = lint('/not-real')
assert_equal 404, status
end
def test_stop
status, _ , app = lint('/stop')
assert_equal :stop, @server.status
assert_equal 200, status
assert_equal ['{ "status": "ok" }'], app.enum_for.to_a
end
def test_halt
status, _ , app = lint('/halt')
assert_equal :halt, @server.status
assert_equal 200, status
assert_equal ['{ "status": "ok" }'], app.enum_for.to_a
end
def test_stats
status, _ , app = lint('/stats')
assert_equal 200, status
assert_equal ['{}'], app.enum_for.to_a
end
def test_alternate_location
status, _ , _ = lint('__alternatE_location_/stats')
assert_equal 200, status
end
def test_disabled_command
@app = Puma::App::Status.new(@server, data_only: true)
status, _ , app = lint('/stats')
assert_equal 200, status
assert_equal ['{}'], app.enum_for.to_a
status, _ , app = lint('/gc-stats')
assert_equal 200, status
status, _ , app = lint('/stop')
assert_equal :running, @server.status
assert_equal 404, status
assert_equal ['Command "stop" unavailable'], app.enum_for.to_a
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_puma_localhost_authority.rb | test/test_puma_localhost_authority.rb | # frozen_string_literal: true
# Nothing in this file runs if Puma isn't compiled with ssl support
#
# helper is required first since it loads Puma, which needs to be
# loaded so HAS_SSL is defined
require_relative "helper"
require "localhost/authority"
if ::Puma::HAS_SSL && !Puma::IS_JRUBY
require "puma/minissl"
require_relative "helpers/test_puma/puma_socket"
require "openssl" unless Object.const_defined? :OpenSSL
end
class TestPumaLocalhostAuthority < PumaTest
include TestPuma
include TestPuma::PumaSocket
def setup
@server = nil
end
def teardown
@server&.stop true
end
# yields ctx to block, use for ctx setup & configuration
def start_server
app = lambda { |env| [200, {}, [env['rack.url_scheme']]] }
@log_writer = SSLLogWriterHelper.new STDOUT, STDERR
@server = Puma::Server.new app, nil, {log_writer: @log_writer}
@server.add_ssl_listener LOCALHOST, 0, nil
@bind_port = @server.connected_ports[0]
@server.run
end
def test_localhost_authority_file_generated
# Initiate server to create localhost authority
unless File.exist?(File.join(Localhost::Authority.path,"localhost.key"))
start_server
end
assert_equal(File.exist?(File.join(Localhost::Authority.path,"localhost.key")), true)
assert_equal(File.exist?(File.join(Localhost::Authority.path,"localhost.crt")), true)
end
end if ::Puma::HAS_SSL && !Puma::IS_JRUBY
class TestPumaSSLLocalhostAuthority < PumaTest
include TestPuma
include TestPuma::PumaSocket
def test_self_signed_by_localhost_authority
app = lambda { |env| [200, {}, [env['rack.url_scheme']]] }
@log_writer = SSLLogWriterHelper.new STDOUT, STDERR
@server = Puma::Server.new app, nil, {log_writer: @log_writer}
@server.app = app
@server.add_ssl_listener LOCALHOST, 0, nil
@bind_port = @server.connected_ports[0]
local_authority_crt = OpenSSL::X509::Certificate.new File.read(File.join(Localhost::Authority.path,"localhost.crt"))
@server.run
cert = nil
begin
cert = send_http(host: LOCALHOST, ctx: new_ctx).peer_cert
rescue OpenSSL::SSL::SSLError, EOFError, Errno::ECONNRESET
# Errno::ECONNRESET TruffleRuby
end
sleep 0.1
assert_equal(cert.to_pem, local_authority_crt.to_pem)
end
end if ::Puma::HAS_SSL && !Puma::IS_JRUBY
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_redirect_io.rb | test/test_redirect_io.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/integration"
class TestRedirectIO < TestIntegration
parallelize_me!
FILE_STR = 'puma startup'
def setup
skip_unless_signal_exist? :HUP
super
# Keep the Tempfile instances alive to avoid being GC'd
@out_file = Tempfile.new('puma-out')
@err_file = Tempfile.new('puma-err')
@out_file_path = @out_file.path
@err_file_path = @err_file.path
@cli_args = ['--redirect-stdout', @out_file_path,
'--redirect-stderr', @err_file_path,
'test/rackup/hello.ru'
]
end
def teardown
return if skipped?
super
paths = (skipped? ? [@out_file_path, @err_file_path] :
[@out_file_path, @err_file_path, @old_out_file_path, @old_err_file_path]).compact
File.unlink(*paths)
@out_file = nil
@err_file = nil
end
def test_sighup_redirects_io_single
skip_if :jruby # Server isn't coming up in CI, TODO Fix
cli_server @cli_args.join ' '
rotate_check_logs
end
def test_sighup_redirects_io_cluster
skip_unless :fork
cli_server (['-w', '1'] + @cli_args).join ' '
rotate_check_logs
end
private
def log_rotate_output_files
# rename both files to .old
@old_out_file_path = "#{@out_file_path}.old"
@old_err_file_path = "#{@err_file_path}.old"
File.rename @out_file_path, @old_out_file_path
File.rename @err_file_path, @old_err_file_path
File.new(@out_file_path, File::CREAT).close
File.new(@err_file_path, File::CREAT).close
end
def rotate_check_logs
assert_file_contents @out_file_path
assert_file_contents @err_file_path
log_rotate_output_files
Process.kill :HUP, @pid
assert_file_contents @out_file_path
assert_file_contents @err_file_path
end
def assert_file_contents(path, include = FILE_STR)
retries = 0
retries_max = 50 # 5 seconds
File.open(path) do |file|
begin
file.read_nonblock 1
file.seek 0
assert_includes file.read, include,
"File #{File.basename(path)} does not include #{include}"
rescue EOFError
sleep 0.1
retries += 1
if retries < retries_max
retry
else
flunk 'File read took too long'
end
end
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_http10.rb | test/test_http10.rb | # frozen_string_literal: true
require_relative "helper"
require "puma/puma_http11"
class Http10ParserTest < PumaTest
def test_parse_simple
parser = Puma::HttpParser.new
req = {}
http = "GET / HTTP/1.0\r\n\r\n"
nread = parser.execute(req, http, 0)
assert nread == http.length, "Failed to parse the full HTTP request"
assert parser.finished?, "Parser didn't finish"
assert !parser.error?, "Parser had error"
assert nread == parser.nread, "Number read returned from execute does not match"
assert_equal '/', req['REQUEST_PATH']
assert_equal 'HTTP/1.0', req['SERVER_PROTOCOL']
assert_equal '/', req['REQUEST_URI']
assert_equal 'GET', req['REQUEST_METHOD']
assert_nil req['FRAGMENT']
assert_nil req['QUERY_STRING']
parser.reset
assert parser.nread == 0, "Number read after reset should be 0"
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_minissl.rb | test/test_minissl.rb | require_relative "helper"
require "puma/minissl" if ::Puma::HAS_SSL
class TestMiniSSL < PumaTest
if Puma.jruby?
def test_raises_with_invalid_keystore_file
ctx = Puma::MiniSSL::Context.new
exception = assert_raises(ArgumentError) { ctx.keystore = "/no/such/keystore" }
assert_equal("Keystore file '/no/such/keystore' does not exist", exception.message)
end
def test_raises_with_unreadable_keystore_file
ctx = Puma::MiniSSL::Context.new
File.stub(:exist?, true) do
File.stub(:readable?, false) do
exception = assert_raises(ArgumentError) { ctx.keystore = "/unreadable/keystore" }
assert_equal("Keystore file '/unreadable/keystore' is not readable", exception.message)
end
end
end
else
def test_raises_with_invalid_key_file
ctx = Puma::MiniSSL::Context.new
exception = assert_raises(ArgumentError) { ctx.key = "/no/such/key" }
assert_equal("Key file '/no/such/key' does not exist", exception.message)
end
def test_raises_with_unreadable_key_file
ctx = Puma::MiniSSL::Context.new
File.stub(:exist?, true) do
File.stub(:readable?, false) do
exception = assert_raises(ArgumentError) { ctx.key = "/unreadable/key" }
assert_equal("Key file '/unreadable/key' is not readable", exception.message)
end
end
end
def test_raises_with_invalid_cert_file
ctx = Puma::MiniSSL::Context.new
exception = assert_raises(ArgumentError) { ctx.cert = "/no/such/cert" }
assert_equal("Cert file '/no/such/cert' does not exist", exception.message)
end
def test_raises_with_unreadable_cert_file
ctx = Puma::MiniSSL::Context.new
File.stub(:exist?, true) do
File.stub(:readable?, false) do
exception = assert_raises(ArgumentError) { ctx.key = "/unreadable/cert" }
assert_equal("Key file '/unreadable/cert' is not readable", exception.message)
end
end
end
def test_raises_with_invalid_key_pem
ctx = Puma::MiniSSL::Context.new
exception = assert_raises(ArgumentError) { ctx.key_pem = nil }
assert_equal("'key_pem' is not a String", exception.message)
end
def test_raises_with_unreadable_ca_file
ctx = Puma::MiniSSL::Context.new
File.stub(:exist?, true) do
File.stub(:readable?, false) do
exception = assert_raises(ArgumentError) { ctx.ca = "/unreadable/cert" }
assert_equal("ca file '/unreadable/cert' is not readable", exception.message)
end
end
end
def test_raises_with_invalid_cert_pem
ctx = Puma::MiniSSL::Context.new
exception = assert_raises(ArgumentError) { ctx.cert_pem = nil }
assert_equal("'cert_pem' is not a String", exception.message)
end
def test_raises_with_invalid_key_password_command
ctx = Puma::MiniSSL::Context.new
ctx.key_password_command = '/unreadable/decrypt_command'
assert_raises(Errno::ENOENT) { ctx.key_password }
end
end
end if ::Puma::HAS_SSL
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_skip_systemd.rb | test/test_skip_systemd.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/integration"
require "puma/plugin"
class TestSkipSystemd < TestIntegration
def setup
skip_unless :linux
skip_if :jruby
super
end
def teardown
super unless skipped?
end
def test_systemd_plugin_not_loaded
cli_server "test/rackup/hello.ru",
env: { 'PUMA_SKIP_SYSTEMD' => 'true', 'NOTIFY_SOCKET' => '/tmp/doesntmatter' }, config: <<~CONFIG
app do |_|
[200, {}, [Puma::Plugins.instance_variable_get(:@plugins)['systemd'].to_s]]
end
CONFIG
assert_empty read_body(connect)
stop_server
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_request_invalid_multiple.rb | test/test_request_invalid_multiple.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/test_puma/puma_socket"
# These tests check for invalid request headers and metadata.
# Content-Length, Transfer-Encoding, and chunked body size
# values are checked for validity
#
# See https://httpwg.org/specs/rfc9112.html
#
# https://httpwg.org/specs/rfc9112.html#body.content-length Content-Length
# https://httpwg.org/specs/rfc9112.html#field.transfer-encoding Transfer-Encoding
# https://httpwg.org/specs/rfc9112.html#chunked.encoding Chunked Transfer Coding
#
class TestRequestInvalidMultiple < PumaTest
# running parallel seems to take longer...
# parallelize_me! unless JRUBY_HEAD
include TestPuma
include TestPuma::PumaSocket
GET_PREFIX = "GET / HTTP/1.1\r\nconnection: close\r\n"
CHUNKED = "1\r\nH\r\n4\r\nello\r\n5\r\nWorld\r\n0\r\n\r\n"
HOST = HOST4
STATUS_CODES = ::Puma::HTTP_STATUS_CODES
HEADERS_413 = [
"Connection: close",
"Content-Length: #{STATUS_CODES[413].bytesize}"
]
def setup
@host = HOST
# this app should never be called, used for debugging
app = ->(env) {
body = +''
env.each do |k,v|
body << "#{k} = #{v}\n"
if k == 'rack.input'
body << "#{v.read}\n"
end
end
[200, {}, [body]]
}
@log_writer = Puma::LogWriter.strings
options = {}
options[:log_writer] = @log_writer
options[:min_threads] = 1
@server = Puma::Server.new app, nil, options
@bind_port = (@server.add_tcp_listener @host, 0).addr[1]
@server.run
sleep 0.15 if Puma::IS_JRUBY
@error_on_closed = if Puma::IS_MRI
if Puma::IS_OSX
[Errno::ECONNRESET, EOFError]
elsif Puma::IS_WINDOWS
[Errno::ECONNABORTED]
else
[EOFError]
end
elsif Puma::IS_OSX && !Puma::IS_JRUBY # TruffleRuby
[Errno::ECONNRESET, EOFError]
else
[EOFError]
end
end
def teardown
@server.stop(true)
end
def server_run(**options, &block)
options[:log_writer] ||= @log_writer
options[:min_threads] ||= 1
@server = Puma::Server.new block || @app, nil, options
@bind_port = (@server.add_tcp_listener @host, 0).addr[1]
@server.run
end
def assert_status(request, status = 400, socket: nil)
response = if socket
socket.req_write(request).read_response
else
socket = new_socket
socket.req_write(request).read_response
end
re = /\AHTTP\/1\.[01] #{status}/
assert_match re, response, "'#{response[/[^\r]+/]}' should be #{status}"
if status >= 400
if @server.leak_stack_on_error
cl = response.headers_hash['content-length'].to_i
refute_equal 0, cl, "Expected `content-length` header to be non-zero but was `#{cl}`. Headers: #{response.headers_hash}"
end
socket.req_write GET_11
assert_raises(*@error_on_closed) { socket.read_response }
end
end
# ──────────────────────────────────── below are oversize path length
def test_oversize_path_keep_alive
path = "/#{'a' * 8_500}"
socket = new_socket
assert_status "GET / HTTP/1.1\r\n\r\n", 200, socket: socket
assert_status "GET #{path} HTTP/1.1\r\n\r\n", socket: socket
end
# ──────────────────────────────────── below are invalid Content-Length
def test_content_length_bad_characters_1_keep_alive
socket = new_socket
assert_status "GET / HTTP/1.1\r\n\r\n", 200, socket: socket
cl = 'Content-Length: 5.01'
assert_status "#{GET_PREFIX}#{cl}\r\n\r\nHello", socket: socket
end
# ──────────────────────────────────── below have http_content_length_limit set
# Sets the server to have a http_content_length_limit of 190 kB, then sends a
# 200 kB body with Content-Length set to the same.
# Verifies that the connection is closed properly.
def __test_http_11_req_oversize_content_length
lleh_err = nil
lleh = -> (err) {
lleh_err = err
[500, {'Content-Type' => 'text/plain'}, ['error']]
}
long_string = 'a' * 200_000
server_run(http_content_length_limit: 190_000, lowlevel_error_handler: lleh) { [200, {}, ['Hello World']] }
socket = send_http "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\nContent-Length: 200000\r\n\r\n" \
"#{long_string}"
response = socket.read_response
# Content Too Large
assert_equal "HTTP/1.1 413 #{STATUS_CODES[413]}", response.status
assert_equal HEADERS_413, response.headers
sleep 0.5
refute lleh_err
assert_raises(Errno::ECONNRESET) { socket << GET_11 }
end
# Sets the server to have a http_content_length_limit of 100 kB, then sends a
# 200 kB chunked body. Verifies that the connection is closed properly.
def __test_http_11_req_oversize_chunked
chunk_length = 20_000
chunk_part_qty = 10
lleh_err = nil
lleh = -> (err) {
lleh_err = err
[500, {'Content-Type' => 'text/plain'}, ['error']]
}
long_string = 'a' * chunk_length
long_string_part = "#{long_string.bytesize.to_s 16}\r\n#{long_string}\r\n"
long_chunked = "#{long_string_part * chunk_part_qty}0\r\n\r\n"
server_run(
http_content_length_limit: 100_000,
lowlevel_error_handler: lleh
) { [200, {}, ['Hello World']] }
socket = send_http "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\n" \
"Transfer-Encoding: chunked\r\n\r\n#{long_chunked}"
response = socket.read_response
# Content Too Large
assert_equal "HTTP/1.1 413 #{STATUS_CODES[413]}", response.status
assert_equal HEADERS_413, response.headers
sleep 0.5
refute lleh_err
assert_raises(Errno::ECONNRESET) { socket << GET_11 }
end
# Sets the server to have a http_content_length_limit of 190 kB, then sends a
# 200 kB body with Content-Length set to the same.
# Verifies that the connection is closed properly.
def __test_http_11_req_oversize_no_content_length
lleh_err = nil
lleh = -> (err) {
lleh_err = err
[500, {'Content-Type' => 'text/plain'}, ['error']]
}
long_string = 'a' * 200_000
server_run(http_content_length_limit: 190_000, lowlevel_error_handler: lleh) { [200, {}, ['Hello World']] }
socket = send_http "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\n\r\n" \
"#{long_string}"
response = socket.read_response
# Content Too Large
assert_equal "HTTP/1.1 413 #{STATUS_CODES[413]}", response.status
assert_equal HEADERS_413, response.headers
sleep 0.5
refute lleh_err
assert_raises(Errno::ECONNRESET) { socket << GET_11 }
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_response_header.rb | test/test_response_header.rb | # frozen_string_literal: true
require_relative "helper"
require "puma/events"
require "net/http"
require "nio"
class TestResponseHeader < PumaTest
parallelize_me!
# this file has limited response length, so 10kB works.
CLIENT_SYSREAD_LENGTH = 10_240
def setup
@host = "127.0.0.1"
@ios = []
@app = ->(env) { [200, {}, [env['rack.url_scheme']]] }
@log_writer = Puma::LogWriter.strings
@server = Puma::Server.new @app, ::Puma::Events.new, {log_writer: @log_writer, min_threads: 1}
end
def teardown
@server.stop(true)
@ios.each { |io| io.close if io && !io.closed? }
end
def server_run(app: @app, early_hints: false)
@server.app = app
@port = (@server.add_tcp_listener @host, 0).addr[1]
@server.instance_variable_set(:@early_hints, true) if early_hints
@server.run
end
def send_http_and_read(req)
send_http(req).sysread CLIENT_SYSREAD_LENGTH
end
def send_http(req)
new_connection << req
end
def new_connection
TCPSocket.new(@host, @port).tap {|sock| @ios << sock}
end
# The header keys must be Strings
def test_integer_key
server_run app: ->(env) { [200, { 1 => 'Boo'}, []] }
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
assert_match(/Puma caught this error/, data)
end
# The header must respond to each
def test_nil_header
server_run app: ->(env) { [200, nil, []] }
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
assert_match(/Puma caught this error/, data)
end
# The values of the header must be Strings
def test_integer_value
server_run app: ->(env) { [200, {'Content-Length' => 500}, []] }
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
assert_match(/HTTP\/1.0 200 OK\r\ncontent-length: 500\r\n\r\n/, data)
end
def assert_ignore_header(name, value, opts={})
header = { name => value }
if opts[:early_hints]
app = ->(env) do
env['rack.early_hints'].call(header)
[200, {}, ['Hello']]
end
else
app = -> (env) { [200, header, ['hello']]}
end
server_run(app: app, early_hints: opts[:early_hints])
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
if opts[:early_hints]
refute_includes data, "HTTP/1.1 103 Early Hints"
end
refute_includes data, "#{name}: #{value}"
end
# The header must not contain a Status key.
def test_status_key
assert_ignore_header("Status", "500")
end
# The header key can contain the word status.
def test_key_containing_status
server_run app: ->(env) { [200, {'teapot-status' => 'Boiling'}, []] }
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
assert_match(/HTTP\/1.0 200 OK\r\nteapot-status: Boiling\r\ncontent-length: 0\r\n\r\n/, data)
end
# Special headers starting “rack.” are for communicating with the server, and must not be sent back to the client.
def test_rack_key
assert_ignore_header("rack.command_to_server_only", "work")
end
# The header key can still start with the word rack
def test_racket_key
server_run app: ->(env) { [200, {'Racket' => 'Bouncy'}, []] }
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
assert_match(/HTTP\/1.0 200 OK\r\nracket: Bouncy\r\ncontent-length: 0\r\n\r\n/, data)
end
# testing header key must conform rfc token specification
# i.e. cannot contain non-printable ASCII, DQUOTE or “(),/:;<=>?@[]{}”.
# Header keys will be set through two ways: Regular and early hints.
def test_illegal_character_in_key
assert_ignore_header("\"F\u0000o\u0025(@o}", "Boo")
end
def test_illegal_character_in_key_when_early_hints
assert_ignore_header("\"F\u0000o\u0025(@o}", "Boo", early_hints: true)
end
# testing header value can be separated by \n into line, and each line must not contain characters below 037
# Header values can be set through three ways: Regular, early hints and a special case for overriding content-length
def test_illegal_character_in_value
assert_ignore_header("X-header", "First \000Lin\037e")
end
def test_illegal_character_in_value_when_early_hints
assert_ignore_header("X-header", "First \000Lin\037e", early_hints: true)
end
def test_illegal_character_in_value_when_override_content_length
assert_ignore_header("Content-Length", "\037")
end
def test_illegal_character_in_value_when_newline
server_run app: ->(env) { [200, {'X-header' => "First\000 line\nSecond Lin\037e"}, ["Hello"]] }
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
refute_match("X-header: First\000 line\r\nX-header: Second Lin\037e\r\n", data)
end
def test_header_value_array
server_run app: ->(env) { [200, {'set-cookie' => ['z=1', 'a=2']}, ['Hello']] }
data = send_http_and_read "GET / HTTP/1.1\r\n\r\n"
resp = "HTTP/1.1 200 OK\r\nset-cookie: z=1\r\nset-cookie: a=2\r\ncontent-length: 5\r\n\r\n"
assert_includes data, resp
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_iobuffer.rb | test/test_iobuffer.rb | # frozen_string_literal: true
require_relative "helper"
require "puma/io_buffer"
class TestIOBuffer < PumaTest
attr_accessor :iobuf
def setup
self.iobuf = Puma::IOBuffer.new
end
def test_initial_size
assert_equal 0, iobuf.size
end
def test_append_op
iobuf << "abc"
assert_equal "abc", iobuf.to_s
iobuf << "123"
assert_equal "abc123", iobuf.to_s
assert_equal 6, iobuf.size
end
def test_append
expected = "mary had a little lamb"
iobuf.append("mary", " ", "had ", "a little", " lamb")
assert_equal expected, iobuf.to_s
assert_equal expected.length, iobuf.size
end
def test_reset
iobuf << "content"
assert_equal "content", iobuf.to_s
iobuf.reset
assert_equal 0, iobuf.size
assert_equal "", iobuf.to_s
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_worker_gem_independence.rb | test/test_worker_gem_independence.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/integration"
class TestWorkerGemIndependence < TestIntegration
ENV_RUBYOPT = {
'RUBYOPT' => ENV['RUBYOPT']
}
def setup
skip_unless :fork
super
end
def teardown
return if skipped?
FileUtils.rm current_release_symlink, force: true
super
end
def test_changing_nio4r_version_during_phased_restart
change_gem_version_during_phased_restart old_app_dir: 'worker_gem_independence_test/old_nio4r',
old_version: '2.7.1',
new_app_dir: 'worker_gem_independence_test/new_nio4r',
new_version: '2.7.2'
end
def test_changing_json_version_during_phased_restart
change_gem_version_during_phased_restart old_app_dir: 'worker_gem_independence_test/old_json',
old_version: '2.7.1',
new_app_dir: 'worker_gem_independence_test/new_json',
new_version: '2.7.0'
end
def test_changing_json_version_during_phased_restart_after_querying_stats_from_status_server
@control_tcp_port = UniquePort.call
server_opts = "--control-url tcp://#{HOST}:#{@control_tcp_port} --control-token #{TOKEN}"
before_restart = ->() do
cli_pumactl "stats"
end
change_gem_version_during_phased_restart server_opts: server_opts,
before_restart: before_restart,
old_app_dir: 'worker_gem_independence_test/old_json',
old_version: '2.7.1',
new_app_dir: 'worker_gem_independence_test/new_json',
new_version: '2.7.0'
end
def test_changing_json_version_during_phased_restart_after_querying_gc_stats_from_status_server
@control_tcp_port = UniquePort.call
server_opts = "--control-url tcp://#{HOST}:#{@control_tcp_port} --control-token #{TOKEN}"
before_restart = ->() do
cli_pumactl "gc-stats"
end
change_gem_version_during_phased_restart server_opts: server_opts,
before_restart: before_restart,
old_app_dir: 'worker_gem_independence_test/old_json',
old_version: '2.7.1',
new_app_dir: 'worker_gem_independence_test/new_json',
new_version: '2.7.0'
end
def test_changing_json_version_during_phased_restart_after_querying_thread_backtraces_from_status_server
@control_tcp_port = UniquePort.call
server_opts = "--control-url tcp://#{HOST}:#{@control_tcp_port} --control-token #{TOKEN}"
before_restart = ->() do
cli_pumactl "thread-backtraces"
end
change_gem_version_during_phased_restart server_opts: server_opts,
before_restart: before_restart,
old_app_dir: 'worker_gem_independence_test/old_json',
old_version: '2.7.1',
new_app_dir: 'worker_gem_independence_test/new_json',
new_version: '2.7.0'
end
def test_changing_json_version_during_phased_restart_after_accessing_puma_stats_directly
change_gem_version_during_phased_restart old_app_dir: 'worker_gem_independence_test/old_json_with_puma_stats_after_fork',
old_version: '2.7.1',
new_app_dir: 'worker_gem_independence_test/new_json_with_puma_stats_after_fork',
new_version: '2.7.0'
end
private
def change_gem_version_during_phased_restart(old_app_dir:,
new_app_dir:,
old_version:,
new_version:,
server_opts: '',
before_restart: nil)
set_release_symlink File.expand_path(old_app_dir, __dir__)
Dir.chdir(current_release_symlink) do
with_unbundled_env do
silent_and_checked_system_command("bundle config --local path vendor/bundle")
silent_and_checked_system_command("bundle install")
cli_server "--prune-bundler -w 1 #{server_opts}", env: ENV_RUBYOPT
end
end
connection = connect
initial_reply = read_body(connection)
assert_equal old_version, initial_reply
before_restart&.call
set_release_symlink File.expand_path(new_app_dir, __dir__)
Dir.chdir(current_release_symlink) do
with_unbundled_env do
silent_and_checked_system_command("bundle config --local path vendor/bundle")
silent_and_checked_system_command("bundle install")
end
end
verify_process_tag(@server.pid, File.basename(old_app_dir))
start_phased_restart
connection = connect
new_reply = read_body(connection)
verify_process_tag(@server.pid, File.basename(new_app_dir))
assert_equal new_version, new_reply
end
def current_release_symlink
File.expand_path "worker_gem_independence_test/current", __dir__
end
def set_release_symlink(target_dir)
FileUtils.rm current_release_symlink, force: true
FileUtils.symlink target_dir, current_release_symlink, force: true
end
def start_phased_restart
Process.kill :USR1, @pid
true while @server.gets !~ /booted in [.0-9]+s, phase: 1/
end
def with_unbundled_env
bundler_ver = Gem::Version.new(Bundler::VERSION)
if bundler_ver < Gem::Version.new('2.1.0')
Bundler.with_clean_env { yield }
else
Bundler.with_unbundled_env { yield }
end
end
def verify_process_tag(pid, tag)
cmd = "ps aux | grep #{pid}"
io = IO.popen cmd, 'r'
assert io.read.include? tag
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_preserve_bundler_env.rb | test/test_preserve_bundler_env.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/integration"
class TestPreserveBundlerEnv < TestIntegration
def setup
skip_unless :fork
super
end
def teardown
return if skipped?
FileUtils.rm current_release_symlink, force: true
super
end
# It does not wipe out BUNDLE_GEMFILE et al
def test_usr2_restart_preserves_bundler_environment
env = {
# Intentionally set this to something we wish to keep intact on restarts
"BUNDLE_GEMFILE" => "Gemfile.bundle_env_preservation_test",
# Don't allow our (rake test's) original env to interfere with the child process
"BUNDLER_ORIG_BUNDLE_GEMFILE" => nil
}
# Must use `bundle exec puma` here, because otherwise Bundler may not be defined, which is required to trigger the bug
cmd = "-w 2 --prune-bundler"
replies = ['', '']
Dir.chdir(File.expand_path("bundle_preservation_test", __dir__)) do
replies = restart_server_and_listen cmd, env: env
end
match = "Gemfile.bundle_env_preservation_test"
assert_match(match, replies[0])
assert_match(match, replies[1])
end
def test_worker_forking_preserves_bundler_config_path
@tcp_port = UniquePort.call
env = {
# Disable the .bundle/config file in the bundle_app_config_test directory
"BUNDLE_APP_CONFIG" => "/dev/null",
# Don't allow our (rake test's) original env to interfere with the child process
"BUNDLE_GEMFILE" => nil,
"BUNDLER_ORIG_BUNDLE_GEMFILE" => nil
}
cmd = "-q -w 1 --prune-bundler"
Dir.chdir File.expand_path("bundle_app_config_test", __dir__) do
cli_server cmd, env: env
end
reply = read_body(connect)
assert_equal("Hello World", reply)
end
def test_phased_restart_preserves_unspecified_bundle_gemfile
@tcp_port = UniquePort.call
env = {
"BUNDLE_GEMFILE" => nil,
"BUNDLER_ORIG_BUNDLE_GEMFILE" => nil
}
set_release_symlink File.expand_path("bundle_preservation_test/version1", __dir__)
cmd = "-q -w 1 --prune-bundler"
Dir.chdir(current_release_symlink) do
cli_server cmd, env: env
end
connection = connect
# Bundler itself sets ENV['BUNDLE_GEMFILE'] to the Gemfile it finds if ENV['BUNDLE_GEMFILE'] was unspecified
initial_reply = read_body(connection)
expected_gemfile = File.expand_path("bundle_preservation_test/version1/Gemfile", __dir__).inspect
assert_equal(expected_gemfile, initial_reply)
set_release_symlink File.expand_path("bundle_preservation_test/version2", __dir__)
start_phased_restart
connection = connect
new_reply = read_body(connection)
expected_gemfile = File.expand_path("bundle_preservation_test/version2/Gemfile", __dir__).inspect
assert_equal(expected_gemfile, new_reply)
end
private
def current_release_symlink
File.expand_path "bundle_preservation_test/current", __dir__
end
def set_release_symlink(target_dir)
FileUtils.rm current_release_symlink, force: true
FileUtils.symlink target_dir, current_release_symlink, force: true
end
def start_phased_restart
Process.kill :USR1, @pid
true while @server.gets !~ /booted in [.0-9]+s, phase: 1/
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_web_server.rb | test/test_web_server.rb | # frozen_string_literal: true
# Copyright (c) 2011 Evan Phoenix
# Copyright (c) 2005 Zed A. Shaw
require_relative "helper"
require "puma/server"
class TestHandler
attr_reader :ran_test
def call(env)
@ran_test = true
[200, {"Content-Type" => "text/plain"}, ["hello!"]]
end
end
class WebServerTest < PumaTest
parallelize_me!
VALID_REQUEST = "GET / HTTP/1.1\r\nHost: www.zedshaw.com\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n"
def setup
@tester = TestHandler.new
@server = Puma::Server.new @tester, nil, {log_writer: Puma::LogWriter.strings}
@port = (@server.add_tcp_listener "127.0.0.1", 0).addr[1]
@tcp = "http://127.0.0.1:#{@port}"
@server.run
end
def teardown
@server.stop(true)
end
def test_simple_server
hit(["#{@tcp}/test"])
assert @tester.ran_test, "Handler didn't really run"
end
def test_requests_count
assert_equal @server.requests_count, 0
3.times do
hit(["#{@tcp}/test"])
end
assert_equal @server.requests_count, 3
end
def test_trickle_attack
socket = do_test(VALID_REQUEST, 3)
assert_match "hello", socket.read
socket.close
end
def test_close_client
assert_raises IOError do
do_test_raise(VALID_REQUEST, 10, 20)
end
end
def test_bad_client
socket = do_test("GET /test HTTP/BAD", 3)
assert_match "Bad Request", socket.read
socket.close
end
def test_bad_path
socket = do_test("GET : HTTP/1.1\r\n\r\n", 3)
data = socket.read
assert_start_with data, "HTTP/1.1 400 Bad Request\r\ncontent-length: "
# match is for last backtrace line, may be brittle
assert_match(/\.rb:\d+:in [`'][^']+'\z/, data)
socket.close
end
def test_header_is_too_long
long = "GET /test HTTP/1.1\r\n" + ("X-Big: stuff\r\n" * 15000) + "\r\n"
assert_raises Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED, Errno::EINVAL, IOError do
do_test_raise(long, long.length/2, 10)
end
end
def test_file_streamed_request
body = "a" * (Puma::Const::MAX_BODY * 2)
long = "GET /test HTTP/1.1\r\nContent-length: #{body.length}\r\nConnection: close\r\n\r\n" + body
socket = do_test(long, (Puma::Const::CHUNK_SIZE * 2) - 400)
assert_match "hello", socket.read
socket.close
end
def test_supported_http_method
socket = do_test("PATCH www.zedshaw.com:443 HTTP/1.1\r\nConnection: close\r\n\r\n", 100)
response = socket.read
assert_match "hello", response
socket.close
end
def test_nonexistent_http_method
socket = do_test("FOOBARBAZ www.zedshaw.com:443 HTTP/1.1\r\nConnection: close\r\n\r\n", 100)
response = socket.read
assert_match "Not Implemented", response
socket.close
end
private
def do_test(string, chunk)
# Do not use instance variables here, because it needs to be thread safe
socket = TCPSocket.new("127.0.0.1", @port);
request = StringIO.new(string)
chunks_out = 0
while data = request.read(chunk)
chunks_out += socket.write(data)
socket.flush
end
socket
end
def do_test_raise(string, chunk, close_after = nil)
# Do not use instance variables here, because it needs to be thread safe
socket = TCPSocket.new("127.0.0.1", @port);
request = StringIO.new(string)
chunks_out = 0
while data = request.read(chunk)
chunks_out += socket.write(data)
socket.flush
socket.close if close_after && chunks_out > close_after
end
socket.write(" ") # Some platforms only raise the exception on attempted write
socket.flush
socket
ensure
socket.close unless socket.closed?
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_cli.rb | test/test_cli.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/ssl" if ::Puma::HAS_SSL
require_relative "helpers/tmp_path"
require_relative "helpers/test_puma/puma_socket"
require "puma/cli"
require "json"
require "psych"
class TestCLI < PumaTest
include SSLHelper if ::Puma::HAS_SSL
include TmpPath
include TestPuma::PumaSocket
def setup
@environment = 'production'
@tmp_path = tmp_path('puma-test')
@tmp_path2 = "#{@tmp_path}2"
File.unlink @tmp_path if File.exist? @tmp_path
File.unlink @tmp_path2 if File.exist? @tmp_path2
@wait, @ready = IO.pipe
@log_writer = Puma::LogWriter.strings
@events = Puma::Events.new
@events.after_booted { @ready << "!" }
@puma_version_pattern = "\\d+.\\d+.\\d+(\\.[a-z\\d]+)?"
end
def wait_booted
@wait.sysread 1
rescue Errno::EAGAIN
sleep 0.001
retry
end
def teardown
File.unlink @tmp_path if File.exist? @tmp_path
File.unlink @tmp_path2 if File.exist? @tmp_path2
@wait.close
@ready.close
end
def check_single_stats(body, check_puma_stats = true)
http_hash = JSON.parse body
dmt = Puma::Configuration::DEFAULTS[:max_threads]
expected_single_root_keys = {
'started_at' => RE_8601,
'backlog' => 0,
'running' => 0,
'pool_capacity' => dmt,
'busy_threads' => 0,
'max_threads' => dmt,
'requests_count' => 0,
'versions' => Hash,
}
assert_hash expected_single_root_keys, http_hash
#version keys
expected_version_hash = {
'puma' => Puma::Const::VERSION,
'ruby' => Hash,
}
assert_hash expected_version_hash, http_hash['versions']
#version ruby keys
expected_version_ruby_hash = {
'engine' => RUBY_ENGINE,
'version' => RUBY_VERSION,
'patchlevel' => RUBY_PATCHLEVEL,
}
assert_hash expected_version_ruby_hash, http_hash['versions']['ruby']
if check_puma_stats
puma_stats_hash = JSON.parse(Puma.stats)
assert_hash expected_single_root_keys, puma_stats_hash
assert_hash expected_version_hash, puma_stats_hash['versions']
assert_hash expected_version_ruby_hash, puma_stats_hash['versions']['ruby']
assert_equal Puma.stats_hash, JSON.parse(Puma.stats, symbolize_names: true)
end
end
def test_control_for_tcp
control_port = UniquePort.call
url = "tcp://127.0.0.1:#{control_port}/"
cli = Puma::CLI.new ["-b", "tcp://127.0.0.1:0",
"--control-url", url,
"--control-token", "",
"test/rackup/hello.ru"], @log_writer, @events
t = Thread.new { cli.run }
wait_booted
body = send_http_read_resp_body "GET /stats HTTP/1.0\r\n\r\n", port: control_port
check_single_stats body
ensure
cli.launcher.stop
t.join
end
def test_control_for_ssl
skip_unless :ssl
require "net/http"
control_port = UniquePort.call
control_host = "127.0.0.1"
control_url = "ssl://#{control_host}:#{control_port}?#{ssl_query}"
token = "token"
cli = Puma::CLI.new ["-b", "tcp://127.0.0.1:0",
"--control-url", control_url,
"--control-token", token,
"test/rackup/hello.ru"], @log_writer, @events
t = Thread.new { cli.run }
wait_booted
body = send_http_read_resp_body "GET /stats?token=#{token} HTTP/1.0\r\n\r\n",
port: control_port, ctx: new_ctx
check_single_stats body
ensure
# always called, even if skipped
cli&.launcher&.stop
t&.join
end
def test_control_for_unix
skip_unless :unix
url = "unix://#{@tmp_path}"
cli = Puma::CLI.new ["-b", "unix://#{@tmp_path2}",
"--control-url", url,
"--control-token", "",
"test/rackup/hello.ru"], @log_writer, @events
t = Thread.new { cli.run }
wait_booted
body = send_http_read_resp_body "GET /stats HTTP/1.0\r\n\r\n", path: @tmp_path
check_single_stats body
ensure
if UNIX_SKT_EXIST
cli.launcher.stop
t.join
end
end
def test_control_stop
skip_unless :unix
url = "unix://#{@tmp_path}"
cli = Puma::CLI.new ["-b", "unix://#{@tmp_path2}",
"--control-url", url,
"--control-token", "",
"test/rackup/hello.ru"], @log_writer, @events
t = Thread.new { cli.run }
wait_booted
body = send_http_read_resp_body "GET /stop HTTP/1.0\r\n\r\n", path: @tmp_path
assert_equal '{ "status": "ok" }', body
ensure
t.join if UNIX_SKT_EXIST
end
def test_control_requests_count
@bind_port = UniquePort.call
control_port = UniquePort.call
url = "tcp://127.0.0.1:#{control_port}/"
cli = Puma::CLI.new ["-b", "tcp://127.0.0.1:#{@bind_port}",
"--control-url", url,
"--control-token", "",
"test/rackup/hello.ru"], @log_writer, @events
t = Thread.new { cli.run }
wait_booted
body = send_http_read_resp_body "GET /stats HTTP/1.0\r\n\r\n", port: control_port
assert_equal 0, JSON.parse(body)['requests_count']
# send real requests to server
3.times { send_http_read_resp_body GET_10 }
body = send_http_read_resp_body "GET /stats HTTP/1.0\r\n\r\n", port: control_port
assert_equal 3, JSON.parse(body)['requests_count']
ensure
cli.launcher.stop
t.join
end
def test_control_thread_backtraces
skip_unless :unix
url = "unix://#{@tmp_path}"
cli = Puma::CLI.new ["-b", "unix://#{@tmp_path2}",
"--control-url", url,
"--control-token", "",
"test/rackup/hello.ru"], @log_writer, @events
t = Thread.new { cli.run }
wait_booted
if TRUFFLE
Thread.pass
sleep 0.2
end
# All thread backtraces may be very large, just get a chunk
socket = send_http "GET /thread-backtraces HTTP/1.0\r\n\r\n", path: @tmp_path
socket.wait_readable 3
body = socket.sysread 32_768
assert_match %r{Thread: TID-}, body
ensure
cli.launcher.stop if cli
t.join if UNIX_SKT_EXIST
end
def test_tmp_control
skip_if :jruby, suffix: " - Unknown issue"
cli = Puma::CLI.new ["--state", @tmp_path, "--control-url", "auto"]
cli.launcher.write_state
opts = cli.launcher.instance_variable_get(:@options)
data = Psych.load_file @tmp_path
Puma::StateFile::ALLOWED_FIELDS.each do |key|
val =
case key
when 'pid' then Process.pid
when 'running_from' then File.expand_path('.') # same as Launcher
else opts[key.to_sym]
end
assert_equal val, data[key]
end
assert_equal (Puma::StateFile::ALLOWED_FIELDS & data.keys).sort, data.keys.sort
url = data["control_url"]
assert_operator url, :start_with?, "unix://", "'#{url}' is not a URL"
end
def test_state_file_callback_filtering
skip_unless :fork
cli = Puma::CLI.new [ "--config", "test/config/state_file_testing_config.rb",
"--state", @tmp_path ]
cli.launcher.write_state
data = Psych.load_file @tmp_path
assert_equal (Puma::StateFile::ALLOWED_FIELDS & data.keys).sort, data.keys.sort
end
def test_log_formatter_default_single
cli = Puma::CLI.new [ ]
assert_instance_of Puma::LogWriter::DefaultFormatter, cli.launcher.log_writer.formatter
end
def test_log_formatter_default_clustered
skip_unless :fork
cli = Puma::CLI.new [ "-w 2" ]
assert_instance_of Puma::LogWriter::PidFormatter, cli.launcher.log_writer.formatter
end
def test_log_formatter_custom_single
cli = Puma::CLI.new [ "--config", "test/config/custom_log_formatter.rb" ]
assert_instance_of Proc, cli.launcher.log_writer.formatter
assert_match(/^\[.*\] \[.*\] .*: test$/, cli.launcher.log_writer.format('test'))
end
def test_log_formatter_custom_clustered
skip_unless :fork
cli = Puma::CLI.new [ "--config", "test/config/custom_log_formatter.rb", "-w 2" ]
assert_instance_of Proc, cli.launcher.log_writer.formatter
assert_match(/^\[.*\] \[.*\] .*: test$/, cli.launcher.log_writer.format('test'))
end
def test_state
url = "tcp://127.0.0.1:#{UniquePort.call}"
cli = Puma::CLI.new ["--state", @tmp_path, "--control-url", url]
cli.launcher.write_state
data = Psych.load_file @tmp_path
assert_equal Process.pid, data["pid"]
assert_equal url, data["control_url"]
end
def test_load_path
Puma::CLI.new ["--include", 'foo/bar']
assert_equal 'foo/bar', $LOAD_PATH[0]
$LOAD_PATH.shift
Puma::CLI.new ["--include", 'foo/bar:baz/qux']
assert_equal 'foo/bar', $LOAD_PATH[0]
$LOAD_PATH.shift
assert_equal 'baz/qux', $LOAD_PATH[0]
$LOAD_PATH.shift
end
def test_extra_runtime_dependencies
cli = Puma::CLI.new ['--extra-runtime-dependencies', 'a,b']
conf = cli.instance_variable_get(:@conf)
conf.clamp
extra_dependencies = conf.options[:extra_runtime_dependencies]
assert_equal %w[a b], extra_dependencies
end
def test_environment_app_env
ENV['RACK_ENV'] = @environment
ENV['RAILS_ENV'] = @environment
ENV['APP_ENV'] = 'test'
cli = Puma::CLI.new []
conf = cli.instance_variable_get(:@conf)
conf.clamp
assert_equal 'test', conf.environment
ensure
ENV.delete 'APP_ENV'
ENV.delete 'RAILS_ENV'
end
def test_environment_rack_env
ENV['RACK_ENV'] = @environment
cli = Puma::CLI.new []
conf = cli.instance_variable_get(:@conf)
conf.clamp
assert_equal @environment, conf.environment
end
def test_environment_rails_env
ENV.delete 'RACK_ENV'
ENV['RAILS_ENV'] = @environment
cli = Puma::CLI.new []
conf = cli.instance_variable_get(:@conf)
conf.clamp
assert_equal @environment, conf.environment
ensure
ENV.delete 'RAILS_ENV'
end
def test_silent
cli = Puma::CLI.new ['--silent']
log_writer = cli.instance_variable_get(:@log_writer)
assert_equal log_writer.class, Puma::LogWriter.null.class
assert_equal log_writer.stdout.class, Puma::NullIO
assert_equal log_writer.stderr, $stderr
end
def test_plugins
assert_empty Puma::Plugins.instance_variable_get(:@plugins)
Puma::CLI.new ['--plugin', 'tmp_restart', '--plugin', 'systemd']
assert Puma::Plugins.find("tmp_restart")
assert Puma::Plugins.find("systemd")
end
def test_config_does_not_preload_app_with_workers
skip_unless :fork
Puma::CLI.new ['-w 0']
config = Puma.cli_config
assert_equal false, config.options[:preload_app]
end
def test_config_preloads_app_with_workers
skip_unless :fork
Puma::CLI.new ['-w 2']
config = Puma.cli_config
assert_equal true, config.options[:preload_app]
end
def test_config_is_advertised_to_config_files
skip_unless :fork
Puma::CLI.new ['-w 2', '-C', File.expand_path('config/cli_config.rb', __dir__)]
assert_equal 4, Puma.cli_config._options[:workers]
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_json_serialization.rb | test/test_json_serialization.rb | # frozen_string_literal: true
require_relative "helper"
require "json"
require "puma/json_serialization"
class TestJSONSerialization < PumaTest
parallelize_me! unless JRUBY_HEAD
def test_json_generates_string_for_hash_with_string_keys
value = { "key" => "value" }
assert_puma_json_generates_string '{"key":"value"}', value
end
def test_json_generates_string_for_hash_with_symbol_keys
value = { key: 'value' }
assert_puma_json_generates_string '{"key":"value"}', value, expected_roundtrip: { "key" => "value" }
end
def test_generate_raises_error_for_unexpected_key_type
value = { [1] => 'b' }
ex = assert_raises Puma::JSONSerialization::SerializationError do
Puma::JSONSerialization.generate value
end
assert_equal 'Could not serialize object of type Array as object key', ex.message
end
def test_json_generates_string_for_array_of_integers
value = [1, 2, 3]
assert_puma_json_generates_string '[1,2,3]', value
end
def test_json_generates_string_for_array_of_strings
value = ["a", "b", "c"]
assert_puma_json_generates_string '["a","b","c"]', value
end
def test_json_generates_string_for_nested_arrays
value = [1, [2, [3]]]
assert_puma_json_generates_string '[1,[2,[3]]]', value
end
def test_json_generates_string_for_integer
value = 42
assert_puma_json_generates_string '42', value
end
def test_json_generates_string_for_float
value = 1.23
assert_puma_json_generates_string '1.23', value
end
def test_json_escapes_strings_with_quotes
value = 'a"'
assert_puma_json_generates_string '"a\""', value
end
def test_json_escapes_strings_with_backslashes
value = 'a\\'
assert_puma_json_generates_string '"a\\\\"', value
end
def test_json_escapes_strings_with_null_byte
value = "\x00"
assert_puma_json_generates_string '"\u0000"', value
end
def test_json_escapes_strings_with_unicode_information_separator_one
value = "\x1f"
assert_puma_json_generates_string '"\u001F"', value
end
def test_json_generates_string_for_true
value = true
assert_puma_json_generates_string 'true', value
end
def test_json_generates_string_for_false
value = false
assert_puma_json_generates_string 'false', value
end
def test_json_generates_string_for_nil
value = nil
assert_puma_json_generates_string 'null', value
end
def test_generate_raises_error_for_unexpected_value_type
value = /abc/
ex = assert_raises Puma::JSONSerialization::SerializationError do
Puma::JSONSerialization.generate value
end
assert_equal 'Unexpected value of type Regexp', ex.message
end
private
def assert_puma_json_generates_string(expected_output, value_to_serialize, expected_roundtrip: nil)
actual_output = Puma::JSONSerialization.generate(value_to_serialize)
assert_equal expected_output, actual_output
if value_to_serialize.nil?
assert_nil ::JSON.parse(actual_output)
else
expected_roundtrip ||= value_to_serialize
assert_equal expected_roundtrip, ::JSON.parse(actual_output)
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_events.rb | test/test_events.rb | # frozen_string_literal: true
require 'puma/events'
require_relative "helper"
class TestEvents < PumaTest
def test_register_callback_with_block
res = false
events = Puma::Events.new
events.register(:exec) { res = true }
events.fire(:exec)
assert_equal true, res
end
def test_register_callback_with_object
obj = Object.new
def obj.res
@res || false
end
def obj.call
@res = true
end
events = Puma::Events.new
events.register(:exec, obj)
events.fire(:exec)
assert_equal true, obj.res
end
def test_fire_callback_with_multiple_arguments
res = []
events = Puma::Events.new
events.register(:exec) { |*args| res.concat(args) }
events.fire(:exec, :foo, :bar, :baz)
assert_equal [:foo, :bar, :baz], res
end
def test_after_booted_callback
res = false
events = Puma::Events.new
events.after_booted { res = true }
events.fire_after_booted!
assert res
end
def test_before_restart_callback
res = false
events = Puma::Events.new
events.before_restart { res = true }
events.fire_before_restart!
assert res
end
def test_after_stopped_callback
res = false
events = Puma::Events.new
events.after_stopped { res = true }
events.fire_after_stopped!
assert res
end
def test_on_booted_deprecated_with_warning
res = false
events = Puma::Events.new
_, err = capture_io do
events.on_booted { res = true }
end
events.fire_after_booted!
assert res
assert_match(/Use 'after_booted', 'on_booted' is deprecated and will be removed in v8/, err)
end
def test_on_restart_deprecated_with_warning
res = false
events = Puma::Events.new
_, err = capture_io do
events.on_restart { res = true }
end
events.fire_before_restart!
assert res
assert_match(/Use 'before_restart', 'on_restart' is deprecated and will be removed in v8/, err)
end
def test_on_stopped_deprecated_with_warning
res = false
events = Puma::Events.new
_, err = capture_io do
events.on_stopped { res = true }
end
events.fire_after_stopped!
assert res
assert_match(/Use 'after_stopped', 'on_stopped' is deprecated and will be removed in v8/, err)
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_plugin.rb | test/test_plugin.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/integration"
class TestPlugin < TestIntegration
def test_plugin
@control_tcp_port = UniquePort.call
Dir.mkdir("tmp") unless Dir.exist?("tmp")
cli_server "--control-url tcp://#{HOST}:#{@control_tcp_port} --control-token #{TOKEN} test/rackup/hello.ru",
config: "plugin 'tmp_restart'"
File.open('tmp/restart.txt', mode: 'wb') { |f| f.puts "Restart #{Time.now}" }
assert wait_for_server_to_include('Restarting...')
assert wait_for_server_to_boot
cli_pumactl "stop"
assert wait_for_server_to_include('Goodbye')
@server.close
@server = nil
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_unix_socket.rb | test/test_unix_socket.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/tmp_path"
class TestPumaUnixSocket < PumaTest
include TmpPath
App = lambda { |env| [200, {}, ["Works"]] }
def teardown
return if skipped?
@server.stop(true)
end
def server_unix(type)
@tmp_socket_path = type == :unix ? tmp_path('.sock') : "@TestPumaUnixSocket"
@server = Puma::Server.new App
@server.add_unix_listener @tmp_socket_path
@server.run
end
def test_server_unix
skip_unless :unix
server_unix :unix
sock = UNIXSocket.new @tmp_socket_path
sock << "GET / HTTP/1.0\r\nHost: blah.com\r\n\r\n"
expected = "HTTP/1.0 200 OK\r\ncontent-length: 5\r\n\r\nWorks"
assert_equal expected, sock.read(expected.size)
end
def test_server_aunix
skip_unless :aunix
server_unix :aunix
sock = UNIXSocket.new @tmp_socket_path.sub(/\A@/, "\0")
sock << "GET / HTTP/1.0\r\nHost: blah.com\r\n\r\n"
expected = "HTTP/1.0 200 OK\r\ncontent-length: 5\r\n\r\nWorks"
assert_equal expected, sock.read(expected.size)
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_integration_ssl.rb | test/test_integration_ssl.rb | # frozen_string_literal: true
require_relative 'helper'
require_relative "helpers/integration"
if ::Puma::HAS_SSL # don't load any files if no ssl support
require "net/http"
require "openssl"
require_relative "helpers/test_puma/puma_socket"
end
# These tests are used to verify that Puma works with SSL sockets. Only
# integration tests isolate the server from the test environment, so there
# should be a few SSL tests.
#
# For instance, since other tests make use of 'client' SSLSockets created by
# net/http, OpenSSL is loaded in the CI process. By shelling out with IO.popen,
# the server process isn't affected by whatever is loaded in the CI process.
class TestIntegrationSSL < TestIntegration
parallelize_me! if ::Puma.mri?
LOCALHOST = ENV.fetch 'PUMA_CI_DFLT_HOST', 'localhost'
include TestPuma::PumaSocket
def bind_port
@bind_port ||= UniquePort.call
@tcp_port = @bind_port
end
def control_tcp_port
@control_tcp_port ||= UniquePort.call
end
def with_server(config)
cli_server "-t1:1", config: config, no_bind: true
http = Net::HTTP.new HOST, bind_port
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
yield http
end
def test_ssl_run
cert_path = File.expand_path '../examples/puma', __dir__
config = <<~CONFIG
if ::Puma.jruby?
keystore = '#{cert_path}/keystore.jks'
keystore_pass = 'jruby_puma'
ssl_bind '#{HOST}', '#{bind_port}', {
keystore: keystore,
keystore_pass: keystore_pass,
verify_mode: 'none'
}
else
key = '#{cert_path}/puma_keypair.pem'
cert = '#{cert_path}/cert_puma.pem'
ssl_bind '#{HOST}', '#{bind_port}', {
cert: cert,
key: key,
verify_mode: 'none'
}
end
activate_control_app 'tcp://#{HOST}:#{control_tcp_port}', { auth_token: '#{TOKEN}' }
app do |env|
[200, {}, [env['rack.url_scheme']]]
end
CONFIG
with_server(config) do |http|
body = nil
http.start do
req = Net::HTTP::Get.new '/', {}
http.request(req) { |resp| body = resp.body }
end
assert_equal 'https', body
end
end
# should use TLSv1.3 with OpenSSL 1.1 or later
def test_verify_client_cert_roundtrip(tls1_2 = nil)
cert_path = File.expand_path '../examples/puma/client_certs', __dir__
bind_port
cli_server "-t1:5 #{set_pumactl_args}", no_bind: true, config: <<~CONFIG
if ::Puma::IS_JRUBY
ssl_bind '#{LOCALHOST}', '#{@bind_port}', {
keystore: '#{cert_path}/keystore.jks',
keystore_pass: 'jruby_puma',
verify_mode: 'force_peer'
}
else
ssl_bind '#{LOCALHOST}', '#{@bind_port}', {
cert: '#{cert_path}/server.crt',
key: '#{cert_path}/server.key',
ca: '#{cert_path}/ca.crt',
verify_mode: 'force_peer'
}
end
threads 1, 5
app do |env|
[200, {}, [env['puma.peercert'].to_s]]
end
CONFIG
client_cert = File.read "#{cert_path}/client.crt"
body = send_http_read_resp_body host: LOCALHOST, port: @bind_port, ctx: new_ctx { |c|
ca = "#{cert_path}/ca.crt"
key = "#{cert_path}/client.key"
c.ca_file = ca
c.cert = ::OpenSSL::X509::Certificate.new client_cert
c.key = ::OpenSSL::PKey::RSA.new File.read(key)
c.verify_mode = ::OpenSSL::SSL::VERIFY_PEER
if tls1_2
if c.respond_to? :max_version=
c.max_version = :TLS1_2
else
c.ssl_version = :TLSv1_2
end
end
}
assert_equal client_cert, body
end
def test_verify_client_cert_roundtrip_tls1_2
test_verify_client_cert_roundtrip true
end
def test_ssl_run_with_curl_client
skip_if :windows
require 'stringio'
cert_path = File.expand_path '../examples/puma/client_certs', __dir__
bind_port
cli_server "-t1:1", no_bind: true, config: <<~CONFIG
if ::Puma::IS_JRUBY
ssl_bind '#{LOCALHOST}', '#{@bind_port}', {
keystore: '#{cert_path}/keystore.jks',
keystore_pass: 'jruby_puma',
verify_mode: 'force_peer'
}
else
ssl_bind '#{LOCALHOST}', '#{@bind_port}', {
cert: '#{cert_path}/server.crt',
key: '#{cert_path}/server.key',
ca: '#{cert_path}/ca.crt',
verify_mode: 'force_peer'
}
end
app { |_| [200, { 'Content-Type' => 'text/plain' }, ["HELLO", ' ', "THERE"]] }
CONFIG
ca = "#{cert_path}/ca.crt"
cert = "#{cert_path}/client.crt"
key = "#{cert_path}/client.key"
# NOTE: JRuby used to end up in a hang with TLS peer verification enabled
# it's easier to reproduce using an external client such as CURL (using net/http client the bug isn't triggered)
# also the "hang", being buffering related, seems to showcase better with TLS 1.2 than 1.3
body = curl_and_get_response "https://#{LOCALHOST}:#{@bind_port}",
args: "--cacert #{ca} --cert #{cert} --key #{key} --tlsv1.2 --tls-max 1.2"
assert_equal 'HELLO THERE', body
end
def test_ssl_run_with_pem
skip_if :jruby
config = <<~CONFIG
key_path = '#{File.expand_path '../examples/puma/puma_keypair.pem', __dir__}'
cert_path = '#{File.expand_path '../examples/puma/cert_puma.pem', __dir__}'
ssl_bind '#{HOST}', '#{bind_port}', {
cert_pem: File.read(cert_path),
key_pem: File.read(key_path),
verify_mode: 'none'
}
activate_control_app 'tcp://#{HOST}:#{control_tcp_port}', { auth_token: '#{TOKEN}' }
app do |env|
[200, {}, [env['rack.url_scheme']]]
end
CONFIG
with_server(config) do |http|
body = nil
http.start do
req = Net::HTTP::Get.new '/', {}
http.request(req) { |resp| body = resp.body }
end
assert_equal 'https', body
end
end
def test_ssl_run_with_localhost_authority
skip_if :jruby
config = <<~CONFIG
require 'localhost'
ssl_bind '#{HOST}', '#{bind_port}'
activate_control_app 'tcp://#{HOST}:#{control_tcp_port}', { auth_token: '#{TOKEN}' }
app do |env|
[200, {}, [env['rack.url_scheme']]]
end
CONFIG
with_server(config) do |http|
body = nil
http.start do
req = Net::HTTP::Get.new '/', {}
http.request(req) { |resp| body = resp.body }
end
assert_equal 'https', body
end
end
def test_ssl_run_with_encrypted_key
skip_if :jruby
cert_path = File.expand_path '../examples/puma', __dir__
config = <<~CONFIG
key_path = '#{cert_path}/encrypted_puma_keypair.pem'
cert_path = '#{cert_path}/cert_puma.pem'
key_command = ::Puma::IS_WINDOWS ? 'echo hello world' :
'#{cert_path}/key_password_command.sh'
ssl_bind '#{HOST}', '#{bind_port}', {
cert: cert_path,
key: key_path,
verify_mode: 'none',
key_password_command: key_command
}
activate_control_app 'tcp://#{HOST}:#{control_tcp_port}', { auth_token: '#{TOKEN}' }
app do |env|
[200, {}, [env['rack.url_scheme']]]
end
CONFIG
with_server(config) do |http|
body = nil
http.start do
req = Net::HTTP::Get.new '/', {}
http.request(req) { |resp| body = resp.body }
end
assert_equal 'https', body
end
end
def test_ssl_run_with_encrypted_pem
skip_if :jruby
cert_path = File.expand_path '../examples/puma', __dir__
config = <<~CONFIG
key_path = '#{cert_path}/encrypted_puma_keypair.pem'
cert_path = '#{cert_path}/cert_puma.pem'
key_command = ::Puma::IS_WINDOWS ? 'echo hello world' :
'#{cert_path}/key_password_command.sh'
ssl_bind '#{HOST}', '#{bind_port}', {
cert_pem: File.read(cert_path),
key_pem: File.read(key_path),
verify_mode: 'none',
key_password_command: key_command
}
activate_control_app 'tcp://#{HOST}:#{control_tcp_port}', { auth_token: '#{TOKEN}' }
app do |env|
[200, {}, [env['rack.url_scheme']]]
end
CONFIG
with_server(config) do |http|
body = nil
http.start do
req = Net::HTTP::Get.new '/', {}
http.request(req) { |resp| body = resp.body }
end
assert_equal 'https', body
end
end
private
def curl_and_get_response(url, method: :get, args: nil); require 'open3'
cmd = "curl -s -v --show-error #{args} -X #{method.to_s.upcase} -k #{url}"
begin
out, err, status = Open3.capture3(cmd)
rescue Errno::ENOENT
fail "curl not available, make sure curl binary is installed and available on $PATH"
end
if status.success?
http_status = err.match(/< HTTP\/1.1 (.*?)/)[1] || '0' # < HTTP/1.1 200 OK\r\n
if http_status.strip[0].to_i > 2
warn out
fail "#{cmd.inspect} unexpected response: #{http_status}\n\n#{err}"
end
return out
else
warn out
fail "#{cmd.inspect} process failed: #{status}\n\n#{err}"
end
end
end if ::Puma::HAS_SSL
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_url_map.rb | test/test_url_map.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/integration"
class TestURLMap < TestIntegration
def teardown
return if skipped?
super
end
# make sure the mapping defined in url_map_test/config.ru works
def test_basic_url_mapping
skip_if :jruby
env = { "BUNDLE_GEMFILE" => "#{__dir__}/url_map_test/Gemfile" }
Dir.chdir("#{__dir__}/url_map_test") do
cli_server set_pumactl_args, env: env
end
connection = connect("/ok")
# Puma 6.2.2 and below will time out here with Ruby v3.3
# see https://github.com/puma/puma/pull/3165
body = read_body(connection, 1)
assert_equal("OK", body)
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_error_logger.rb | test/test_error_logger.rb | # frozen_string_literal: true
require 'puma/error_logger'
require_relative "helper"
class TestErrorLogger < PumaTest
Req = Struct.new(:env, :body)
def test_stdio
error_logger = Puma::ErrorLogger.stdio
assert_equal STDERR, error_logger.ioerr
end
def test_stdio_respects_sync
error_logger = Puma::ErrorLogger.stdio
assert_equal STDERR.sync, error_logger.ioerr.sync
assert_equal STDERR, error_logger.ioerr
end
def test_info_with_only_error
_, err = capture_io do
Puma::ErrorLogger.stdio.info(error: StandardError.new('ready'))
end
assert_includes err, '#<StandardError: ready>'
end
def test_info_with_request
env = {
'REQUEST_METHOD' => 'GET',
'PATH_INFO' => '/debug',
'HTTP_X_FORWARDED_FOR' => '8.8.8.8'
}
req = Req.new(env, '{"hello":"world"}')
_, err = capture_io do
Puma::ErrorLogger.stdio.info(error: StandardError.new, req: req)
end
assert_includes err, '("GET /debug" - (8.8.8.8))'
end
def test_info_with_request_with_query_param
env = {
'REQUEST_METHOD' => 'GET',
'PATH_INFO' => '/debug',
'HTTP_X_FORWARDED_FOR' => '8.8.8.8',
'QUERY_STRING' => 'b=test'
}
req = Req.new(env, '{"hello":"world"}')
_, err = capture_io do
Puma::ErrorLogger.stdio.info(error: StandardError.new, req: req)
end
assert_includes err, 'GET /debug?b=test" - (8.8.8.8))'
end
def test_info_with_text
_, err = capture_io do
Puma::ErrorLogger.stdio.info(text: 'The client disconnected while we were reading data')
end
assert_includes err, 'The client disconnected while we were reading data'
end
def test_debug_without_debug_mode
_, err = capture_io do
Puma::ErrorLogger.stdio.debug(text: 'blank')
end
assert_empty err
end
def test_debug_with_debug_mode
with_debug_mode do
_, err = capture_io do
Puma::ErrorLogger.stdio.debug(text: 'non-blank')
end
assert_includes err, 'non-blank'
end
end
def test_debug_backtrace_logging
with_debug_mode do
def dummy_error
raise StandardError.new('non-blank')
rescue => e
Puma::ErrorLogger.stdio.debug(error: e)
end
_, err = capture_io do
dummy_error
end
assert_includes err, "non-blank"
include_str =
case
when Puma::IS_MRI && RUBY_VERSION < '3.4' || TRUFFLE
":in `dummy_error'" # beginning backtick
when Puma::IS_JRUBY
":in 'dummy_error'" # beginning apostrophe/single quote
else
":in 'TestErrorLogger#dummy_error'"
end
assert_includes err, include_str
end
end
private
def with_debug_mode
original_debug, ENV["PUMA_DEBUG"] = ENV["PUMA_DEBUG"], "1"
yield
ensure
ENV["PUMA_DEBUG"] = original_debug
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_launcher.rb | test/test_launcher.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/tmp_path"
require "puma/configuration"
require 'puma/log_writer'
# Do not add any tests creating workers to this, as Cluster may call `Process.waitall`,
# which may cause issues in the test process.
# Intermittent failures & errors when run parallel in GHA, local use may run fine.
class TestLauncher < PumaTest
include TmpPath
def test_prints_thread_traces
create_launcher.thread_status do |name, _backtrace|
assert_match "Thread: TID", name
end
end
def test_pid_file
pid_path = tmp_path('.pid')
conf = Puma::Configuration.new do |c|
c.pidfile pid_path
end
create_launcher(conf).write_state
assert_equal File.read(pid_path).strip.to_i, Process.pid
ensure
File.unlink pid_path
end
def test_state_permission_0640
state_path = nil
skip_if :windows # only 0644 ?
state_path = tmp_path('.state')
state_permission = 0640
conf = Puma::Configuration.new do |c|
c.state_path state_path
c.state_permission state_permission
end
create_launcher(conf).write_state
assert_equal state_permission.to_s(8), File.stat(state_path).mode.to_s(8)[-3..-1]
ensure
File.unlink(state_path) if state_path
end
def test_state_permission_nil
state_path = tmp_path('.state')
conf = Puma::Configuration.new do |c|
c.state_path state_path
c.state_permission nil
end
create_launcher(conf).write_state
assert File.exist?(state_path)
ensure
File.unlink state_path
end
def test_no_state_permission
state_path = tmp_path('.state')
conf = Puma::Configuration.new do |c|
c.state_path state_path
end
create_launcher(conf).write_state
assert File.exist?(state_path)
ensure
File.unlink state_path
end
def test_puma_stats
conf = Puma::Configuration.new do |c|
c.app -> {[200, {}, ['']]}
end
launcher = create_launcher(conf)
launcher.events.after_booted {
sleep 1.1 unless Puma.mri?
launcher.stop
}
launcher.stats # Ensure `stats` method return without errors before run
launcher.run
sleep 1 unless Puma.mri?
Puma::Server::STAT_METHODS.each do |stat|
assert_includes launcher.stats, stat
end
end
def test_log_config_enabled
env = {'PUMA_LOG_CONFIG' => '1'}
launcher = create_launcher env: env
log = launcher.log_writer.stdout.string
# the below confirms an exact match, allowing for line order differences
launcher.config.final_options.each do |config_key, value|
line = "- #{config_key}: #{value}\n"
assert_includes log, line
log.sub! line, ''
end
assert_equal 'Configuration:', log.strip
end
def test_log_config_disabled
refute_match(/Configuration:/, create_launcher.log_writer.stdout.string)
end
def test_fire_after_stopped
conf = Puma::Configuration.new do |c|
c.app -> {[200, {}, ['']]}
end
is_stopped = nil
launcher = create_launcher(conf)
launcher.events.after_booted {
sleep 1.1 unless Puma.mri?
launcher.stop
}
launcher.events.after_stopped { is_stopped = true }
launcher.run
sleep 0.2 unless Puma.mri?
assert is_stopped, "after_stopped not called"
end
private
def create_launcher(config = Puma::Configuration.new, lw = Puma::LogWriter.strings, **kw)
config.configure do |c|
c.bind "tcp://127.0.0.1:#{UniquePort.call}"
end
Puma::Launcher.new(config, log_writer: lw, **kw)
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_config.rb | test/test_config.rb | # frozen_string_literal: true
require_relative "helper"
require "puma/configuration"
require 'puma/log_writer'
require 'rack'
class TestConfigFile < PumaTest
parallelize_me!
def test_default_max_threads
max_threads = 16
max_threads = 5 if RUBY_ENGINE.nil? || RUBY_ENGINE == 'ruby'
conf = Puma::Configuration.new
conf.clamp
assert_equal max_threads, conf.options.default_options[:max_threads]
end
def test_app_from_rackup
if Rack.release >= '3'
fn = "test/rackup/hello-bind_rack3.ru"
bind = "tcp://0.0.0.0:9292"
else
fn = "test/rackup/hello-bind.ru"
bind = "tcp://127.0.0.1:9292"
end
conf = Puma::Configuration.new do |c|
c.rackup fn
end
conf.clamp
# suppress deprecation warning of Rack (>= 2.2.0)
# > Parsing options from the first comment line is deprecated!\n
assert_output(nil, nil) do
conf.app
end
assert_equal [200, {"Content-Type"=>"text/plain"}, ["Hello World"]], conf.app.call({})
assert_equal [bind], conf.options[:binds]
end
def test_app_from_app_DSL
conf = Puma::Configuration.new do |c|
c.load "test/config/app.rb"
end
conf.clamp
app = conf.app
assert_equal [200, {}, ["embedded app"]], app.call({})
end
def test_ssl_configuration_from_DSL
skip_unless :ssl
conf = Puma::Configuration.new do |config|
config.load "test/config/ssl_config.rb"
end
conf.clamp
bind_configuration = conf.options.file_options[:binds].first
app = conf.app
assert bind_configuration =~ %r{ca=.*ca.crt}
assert bind_configuration&.include?('verify_mode=peer')
assert_equal [200, {}, ["embedded app"]], app.call({})
end
def test_ssl_self_signed_configuration_from_DSL
skip_if :jruby
skip_unless :ssl
conf = Puma::Configuration.new do |config|
config.load "test/config/ssl_self_signed_config.rb"
end
conf.clamp
ssl_binding = "ssl://0.0.0.0:9292?&verify_mode=none"
assert_equal [ssl_binding], conf.options[:binds]
end
def test_ssl_bind
skip_if :jruby
skip_unless :ssl
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
cert: "/path/to/cert",
key: "/path/to/key",
verify_mode: "the_verify_mode",
}
end
conf.clamp
ssl_binding = "ssl://0.0.0.0:9292?cert=%2Fpath%2Fto%2Fcert&key=%2Fpath%2Fto%2Fkey&verify_mode=the_verify_mode"
assert_equal [ssl_binding], conf.options[:binds]
end
def test_ssl_bind_with_escaped_filenames
skip_if :jruby
skip_unless :ssl
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
cert: "/path/to/cert+1",
ca: "/path/to/ca+1",
key: "/path/to/key+1",
verify_mode: :peer
}
end
conf.clamp
ssl_binding = "ssl://0.0.0.0:9292?cert=%2Fpath%2Fto%2Fcert%2B1&key=%2Fpath%2Fto%2Fkey%2B1&verify_mode=peer&ca=%2Fpath%2Fto%2Fca%2B1"
assert_equal [ssl_binding], conf.options[:binds]
end
def test_ssl_bind_with_cert_and_key_pem
skip_if :jruby
skip_unless :ssl
cert_path = File.expand_path "../examples/puma/client_certs", __dir__
cert_pem = File.read("#{cert_path}/server.crt")
key_pem = File.read("#{cert_path}/server.key")
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
cert_pem: cert_pem,
key_pem: key_pem,
verify_mode: "the_verify_mode",
}
end
conf.clamp
ssl_binding = "ssl://0.0.0.0:9292?cert=store%3A0&key=store%3A1&verify_mode=the_verify_mode"
assert_equal [ssl_binding], conf.options[:binds]
end
def test_ssl_bind_with_backlog
skip_unless :ssl
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
backlog: "2048",
}
end
conf.clamp
ssl_binding = conf.options[:binds].first
assert ssl_binding.include?('&backlog=2048')
end
def test_ssl_bind_with_low_latency_true
skip_unless :ssl
skip_if :jruby
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
low_latency: true
}
end
conf.clamp
ssl_binding = conf.options[:binds].first
assert ssl_binding.include?('&low_latency=true')
end
def test_ssl_bind_with_low_latency_false
skip_unless :ssl
skip_if :jruby
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
low_latency: false
}
end
conf.clamp
ssl_binding = conf.options[:binds].first
assert ssl_binding.include?('&low_latency=false')
end
def test_ssl_bind_jruby
skip_unless :jruby
skip_unless :ssl
ciphers = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
keystore: "/path/to/keystore",
keystore_pass: "password",
cipher_suites: ciphers,
protocols: 'TLSv1.2',
verify_mode: "the_verify_mode"
}
end
conf.clamp
ssl_binding = "ssl://0.0.0.0:9292?keystore=/path/to/keystore" \
"&keystore-pass=password&cipher_suites=#{ciphers}&protocols=TLSv1.2" \
"&verify_mode=the_verify_mode"
assert_equal [ssl_binding], conf.options[:binds]
end
def test_ssl_bind_jruby_with_ssl_cipher_list
skip_unless :jruby
skip_unless :ssl
cipher_list = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
keystore: "/path/to/keystore",
keystore_pass: "password",
ssl_cipher_list: cipher_list,
verify_mode: "the_verify_mode"
}
end
conf.clamp
ssl_binding = "ssl://0.0.0.0:9292?keystore=/path/to/keystore" \
"&keystore-pass=password&ssl_cipher_list=#{cipher_list}" \
"&verify_mode=the_verify_mode"
assert_equal [ssl_binding], conf.options[:binds]
end
def test_ssl_bind_jruby_with_truststore
skip_unless :jruby
skip_unless :ssl
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
keystore: "/path/to/keystore",
keystore_type: "pkcs12",
keystore_pass: "password",
truststore: "default",
truststore_type: "jks",
verify_mode: "none"
}
end
conf.clamp
ssl_binding = "ssl://0.0.0.0:9292?keystore=/path/to/keystore" \
"&keystore-pass=password&keystore-type=pkcs12" \
"&truststore=default&truststore-type=jks" \
"&verify_mode=none"
assert_equal [ssl_binding], conf.options[:binds]
end
def test_ssl_bind_no_tlsv1_1
skip_if :jruby
skip_unless :ssl
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
cert: "/path/to/cert",
key: "/path/to/key",
verify_mode: "the_verify_mode",
no_tlsv1_1: true
}
end
conf.clamp
ssl_binding = "ssl://0.0.0.0:9292?cert=%2Fpath%2Fto%2Fcert&key=%2Fpath%2Fto%2Fkey&verify_mode=the_verify_mode&no_tlsv1_1=true"
assert_equal [ssl_binding], conf.options[:binds]
end
def test_ssl_bind_with_cipher_filter
skip_if :jruby
skip_unless :ssl
cipher_filter = "!aNULL:AES+SHA"
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
cert: "cert",
key: "key",
ssl_cipher_filter: cipher_filter,
}
end
conf.clamp
ssl_binding = conf.options[:binds].first
assert ssl_binding.include?("&ssl_cipher_filter=#{cipher_filter}")
end
def test_ssl_bind_with_ciphersuites
skip_if :jruby
skip_unless :ssl
skip('Requires TLSv1.3') unless Puma::MiniSSL::HAS_TLS1_3
ciphersuites = "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256"
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
cert: "cert",
key: "key",
ssl_ciphersuites: ciphersuites,
}
end
conf.clamp
ssl_binding = conf.options[:binds].first
assert ssl_binding.include?("&ssl_ciphersuites=#{ciphersuites}")
end
def test_ssl_bind_with_verification_flags
skip_if :jruby
skip_unless :ssl
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
cert: "cert",
key: "key",
verification_flags: ["TRUSTED_FIRST", "NO_CHECK_TIME"]
}
end
conf.clamp
ssl_binding = conf.options[:binds].first
assert ssl_binding.include?("&verification_flags=TRUSTED_FIRST,NO_CHECK_TIME")
end
def test_ssl_bind_with_ca
skip_unless :ssl
conf = Puma::Configuration.new do |c|
c.ssl_bind "0.0.0.0", "9292", {
cert: "/path/to/cert",
ca: "/path/to/ca",
key: "/path/to/key",
verify_mode: :peer,
}
end
conf.clamp
ssl_binding = conf.options[:binds].first
assert_includes ssl_binding, Puma::Util.escape("/path/to/ca")
assert_includes ssl_binding, "verify_mode=peer"
end
def test_lowlevel_error_handler_DSL
conf = Puma::Configuration.new do |c|
c.load "test/config/app.rb"
end
conf.clamp
app = conf.options[:lowlevel_error_handler]
assert_equal [200, {}, ["error page"]], app.call({})
end
def test_allow_users_to_override_default_options
conf = Puma::Configuration.new(restart_cmd: 'bin/rails server')
conf.clamp
assert_equal 'bin/rails server', conf.options[:restart_cmd]
end
def test_overwrite_options
conf = Puma::Configuration.new do |c|
c.workers 3
end
conf.clamp
assert_equal conf.options[:workers], 3
conf.options[:workers] += 1
assert_equal conf.options[:workers], 4
end
def test_explicit_config_files
conf = Puma::Configuration.new(config_files: ['test/config/settings.rb'])
conf.clamp
assert_match(/:3000$/, conf.options[:binds].first)
end
def test_parameters_overwrite_files
conf = Puma::Configuration.new(config_files: ['test/config/settings.rb']) do |c|
c.port 3030
end
conf.clamp
assert_match(/:3030$/, conf.options[:binds].first)
assert_equal 3, conf.options[:min_threads]
assert_equal 5, conf.options[:max_threads]
end
def test_config_files_default
conf = Puma::Configuration.new
conf.clamp
assert_equal [nil], conf.config_files
end
def test_config_files_with_dash
conf = Puma::Configuration.new(config_files: ['-'])
conf.clamp
assert_equal [], conf.config_files
end
def test_config_files_with_existing_path
conf = Puma::Configuration.new(config_files: ['test/config/settings.rb'])
conf.clamp
assert_equal ['test/config/settings.rb'], conf.config_files
end
def test_config_files_with_non_existing_path
conf = Puma::Configuration.new(config_files: ['test/config/typo/settings.rb'])
assert_raises Errno::ENOENT do
conf.clamp
end
end
def test_config_files_with_integer_convert
conf = Puma::Configuration.new(config_files: ['test/config/with_integer_convert.rb'])
conf.clamp
assert_equal 6, conf.options[:persistent_timeout]
assert_equal 3, conf.options[:first_data_timeout]
assert_equal 2, conf.options[:workers]
assert_equal 4, conf.options[:min_threads]
assert_equal 8, conf.options[:max_threads]
assert_equal 90, conf.options[:worker_timeout]
assert_equal 120, conf.options[:worker_boot_timeout]
assert_equal 150, conf.options[:worker_shutdown_timeout]
end
def test_config_files_max_keep_alive_infinity
conf = Puma::Configuration.new(config_files: ['test/config/max_keep_alive_infinity.rb']) do
end
conf.clamp
assert_equal Float::INFINITY, conf.options[:max_keep_alive]
end
def test_config_max_keep_alive_infinity
conf = Puma::Configuration.new(config_files: ['test/config/max_keep_alive_infinity.rb']) do
end
conf.clamp
assert_equal Float::INFINITY, conf.options[:max_keep_alive]
end
def test_config_files_with_symbol_convert
conf = Puma::Configuration.new(config_files: ['test/config/with_symbol_convert.rb'])
conf.clamp
assert_equal :ruby, conf.options[:io_selector_backend]
end
def test_config_raise_exception_on_sigterm
conf = Puma::Configuration.new do |c|
c.raise_exception_on_sigterm false
end
conf.clamp
assert_equal conf.options[:raise_exception_on_sigterm], false
conf.options[:raise_exception_on_sigterm] = true
assert_equal conf.options[:raise_exception_on_sigterm], true
end
def test_run_hooks_before_restart_hook
assert_run_hooks :before_restart
assert_run_hooks :before_restart, configured_with: :before_restart
assert_raise_on_hooks_without_block :before_restart
end
def test_run_hooks_before_worker_fork
assert_run_hooks :before_worker_fork, configured_with: :before_worker_fork
assert_raise_on_hooks_without_block :before_worker_fork
assert_warning_for_hooks_defined_in_single_mode :before_worker_fork
end
def test_run_hooks_after_worker_fork
assert_run_hooks :after_worker_fork
assert_raise_on_hooks_without_block :after_worker_fork
assert_warning_for_hooks_defined_in_single_mode :after_worker_fork
end
def test_run_hooks_before_worker_boot
assert_run_hooks :before_worker_boot
assert_run_hooks :before_worker_boot, configured_with: :before_worker_boot
assert_raise_on_hooks_without_block :before_worker_boot
assert_warning_for_hooks_defined_in_single_mode :before_worker_boot
end
def test_run_hooks_before_worker_shutdown
assert_run_hooks :before_worker_shutdown
assert_run_hooks :before_worker_shutdown, configured_with: :before_worker_shutdown
assert_raise_on_hooks_without_block :before_worker_shutdown
assert_warning_for_hooks_defined_in_single_mode :before_worker_shutdown
end
def test_run_hooks_before_fork
assert_run_hooks :before_fork
assert_raise_on_hooks_without_block :before_fork
assert_warning_for_hooks_defined_in_single_mode :before_fork
end
def test_run_hooks_before_refork
assert_run_hooks :before_refork
assert_run_hooks :before_refork, configured_with: :before_refork
assert_raise_on_hooks_without_block :before_refork
assert_warning_for_hooks_defined_in_single_mode :before_refork
end
def test_run_hooks_before_thread_start
assert_run_hooks :before_thread_start
assert_run_hooks :before_thread_start, configured_with: :before_thread_start
assert_raise_on_hooks_without_block :before_thread_start
end
def test_run_hooks_before_thread_exit
assert_run_hooks :before_thread_exit
assert_run_hooks :before_thread_exit, configured_with: :before_thread_exit
assert_raise_on_hooks_without_block :before_thread_exit
end
def test_run_hooks_out_of_band
assert_run_hooks :out_of_band
assert_raise_on_hooks_without_block :out_of_band
end
def test_run_hooks_and_exception
conf = Puma::Configuration.new do |c|
c.before_restart do |a|
raise RuntimeError, 'Error from hook'
end
end
conf.clamp
log_writer = Puma::LogWriter.strings
conf.run_hooks(:before_restart, 'ARG', log_writer)
expected = /WARNING hook before_restart failed with exception \(RuntimeError\) Error from hook/
assert_match expected, log_writer.stdout.string
end
def test_config_does_not_load_workers_by_default
conf = Puma::Configuration.new
conf.clamp
assert_equal 0, conf.options.default_options[:workers]
end
def test_final_options_returns_merged_options
conf = Puma::Configuration.new({ min_threads: 1, max_threads: 2 }, { min_threads: 2 })
conf.clamp
assert_equal 1, conf.final_options[:min_threads]
assert_equal 2, conf.final_options[:max_threads]
end
def test_silence_single_worker_warning_default
conf = Puma::Configuration.new
conf.clamp
assert_equal false, conf.options[:silence_single_worker_warning]
end
def test_silence_single_worker_warning_overwrite
conf = Puma::Configuration.new do |c|
c.silence_single_worker_warning
end
conf.clamp
assert_equal true, conf.options[:silence_single_worker_warning]
end
def test_silence_fork_callback_warning_default
conf = Puma::Configuration.new
conf.clamp
assert_equal false, conf.options[:silence_fork_callback_warning]
end
def test_silence_fork_callback_warning_overwrite
conf = Puma::Configuration.new do |c|
c.silence_fork_callback_warning
end
conf.clamp
assert_equal true, conf.options[:silence_fork_callback_warning]
end
def test_http_content_length_limit
conf = Puma::Configuration.new
conf.clamp
assert_nil conf.options.default_options[:http_content_length_limit]
conf = Puma::Configuration.new({ http_content_length_limit: 10000})
conf.clamp
assert_equal 10000, conf.final_options[:http_content_length_limit]
end
def test_options_raises_not_clamped_error_when_not_clamped
conf = Puma::Configuration.new
error = assert_raises(Puma::Configuration::NotClampedError) do
conf.options
end
assert_equal "ensure clamp is called before accessing options", error.message
end
def test_options_succeeds_when_clamped
conf = Puma::Configuration.new
conf.clamp
assert_kind_of Puma::UserFileDefaultOptions, conf.options
end
def test_config_files_raises_not_loaded_error_when_not_loaded
conf = Puma::Configuration.new
error = assert_raises(Puma::Configuration::NotLoadedError) do
conf.config_files
end
assert_equal "ensure load is called before accessing config_files", error.message
end
def test_config_files_succeeds_when_clamped
conf = Puma::Configuration.new
conf.clamp
assert_kind_of Array, conf.config_files
end
def test_config_does_not_preload_app_if_not_using_workers
conf = Puma::Configuration.new({ workers: 0 })
conf.clamp
assert_equal false, conf.options.default_options[:preload_app]
end
def test_config_preloads_app_if_using_workers
conf = Puma::Configuration.new({ workers: 2 })
conf.clamp
preload = Puma.forkable?
assert_equal preload, conf.options.default_options[:preload_app]
end
def test_config_does_not_preload_app_if_using_workers_and_prune_bundler
conf = Puma::Configuration.new({ workers: 2 }) do |c|
c.prune_bundler
end
conf.clamp
assert_equal false, conf.options.default_options[:preload_app]
end
def test_config_file_does_not_preload_app_if_not_using_workers
conf = Puma::Configuration.new { |c| c.load 'test/config/workers_0.rb' }
conf.clamp
assert_equal false, conf.options.default_options[:preload_app]
end
def test_config_file_preloads_app_if_using_workers
conf = Puma::Configuration.new { |c| c.load 'test/config/workers_2.rb' }
conf.clamp
preload = Puma.forkable?
assert_equal preload, conf.options.default_options[:preload_app]
end
private
def assert_run_hooks(hook_name, options = {})
configured_with = options[:configured_with] || hook_name
# test single, not an array
messages = []
conf = Puma::Configuration.new do |c|
c.silence_fork_callback_warning
c.send(configured_with) do |a|
messages << "#{hook_name} is called with #{a}"
end
end
conf.clamp
conf.run_hooks(hook_name, 'ARG', Puma::LogWriter.strings)
assert_equal ["#{hook_name} is called with ARG"], messages
# test multiple
messages = []
conf = Puma::Configuration.new do |c|
c.silence_fork_callback_warning
c.send(configured_with) do |a|
messages << "#{hook_name} is called with #{a} one time"
end
c.send(configured_with) do |a|
messages << "#{hook_name} is called with #{a} a second time"
end
end
conf.clamp
conf.run_hooks(hook_name, 'ARG', Puma::LogWriter.strings)
assert_equal ["#{hook_name} is called with ARG one time", "#{hook_name} is called with ARG a second time"], messages
end
def assert_raise_on_hooks_without_block(hook_name)
error = assert_raises ArgumentError do
Puma::Configuration.new { |c| c.send(hook_name) }.clamp
end
assert_equal "expected #{hook_name} to be given a block", error.message
end
def assert_warning_for_hooks_defined_in_single_mode(hook_name)
out, _ = capture_io do
conf = Puma::Configuration.new do |c|
c.send(hook_name) do
# noop
end
end
conf.clamp
end
assert_match(/Warning: The code in the `#{hook_name}` block will not execute in the current Puma configuration/, out)
end
end
# contains tests that cannot run parallel
class TestConfigFileSingle < PumaTest
def test_custom_logger_from_DSL
conf = Puma::Configuration.new { |c| c.load 'test/config/custom_logger.rb' }
conf.clamp
out, _ = capture_subprocess_io { conf.options[:custom_logger].write 'test' }
assert_equal "Custom logging: test\n", out
end
end
# Thread unsafe modification of ENV
class TestEnvModifificationConfig < PumaTest
def test_double_bind_port
port = (rand(10_000) + 30_000).to_s
env = { "PORT" => port }
conf = Puma::Configuration.new({}, {}, env) do |user_config, file_config, default_config|
user_config.bind "tcp://#{Puma::Configuration::DEFAULTS[:tcp_host]}:#{port}"
file_config.load "test/config/app.rb"
end
conf.clamp
assert_equal ["tcp://0.0.0.0:#{port}"], conf.options[:binds]
end
end
class TestConfigEnvVariables < PumaTest
def test_config_loads_correct_persistent_timeout
conf = Puma::Configuration.new
conf.clamp
assert_equal 65, conf.options.default_options[:persistent_timeout]
env = { "PUMA_PERSISTENT_TIMEOUT" => "95" }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal 95, conf.options.default_options[:persistent_timeout]
end
def test_config_loads_correct_min_threads
conf = Puma::Configuration.new
conf.clamp
assert_equal 0, conf.options.default_options[:min_threads]
env = { "MIN_THREADS" => "7" }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal 7, conf.options.default_options[:min_threads]
env = { "PUMA_MIN_THREADS" => "8" }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal 8, conf.options.default_options[:min_threads]
env = { "PUMA_MIN_THREADS" => "" }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal 0, conf.options.default_options[:min_threads]
end
def test_config_loads_correct_max_threads
default_max_threads = Puma.mri? ? 5 : 16
conf = Puma::Configuration.new
conf.clamp
assert_equal default_max_threads, conf.options.default_options[:max_threads]
env = { "MAX_THREADS" => "7" }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal 7, conf.options.default_options[:max_threads]
env = { "PUMA_MAX_THREADS" => "8" }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal 8, conf.options.default_options[:max_threads]
env = { "PUMA_MAX_THREADS" => "" }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal default_max_threads, conf.options.default_options[:max_threads]
end
def test_config_loads_workers_from_env
env = { "WEB_CONCURRENCY" => "9" }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal 9, conf.options.default_options[:workers]
end
def test_config_ignores_blank_workers_from_env
env = { "WEB_CONCURRENCY" => "" }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal 0, conf.options.default_options[:workers]
end
def test_config_does_not_preload_app_if_not_using_workers
env = { "WEB_CONCURRENCY" => "0" }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal false, conf.options.default_options[:preload_app]
end
def test_config_preloads_app_if_using_workers
env = { "WEB_CONCURRENCY" => "2" }
preload = Puma.forkable?
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal preload, conf.options.default_options[:preload_app]
end
end
class TestConfigFileWithFakeEnv < PumaTest
def setup
FileUtils.mkpath("config/puma")
File.write("config/puma/fake-env.rb", "")
end
def teardown
FileUtils.rm_r("config/puma")
end
def test_config_files_with_app_env
env = { 'APP_ENV' => 'fake-env' }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal ['config/puma/fake-env.rb'], conf.config_files
end
def test_config_files_with_rack_env
env = { 'RACK_ENV' => 'fake-env' }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal ['config/puma/fake-env.rb'], conf.config_files
end
def test_config_files_with_rails_env
env = { 'RAILS_ENV' => 'fake-env', 'RACK_ENV' => nil }
conf = Puma::Configuration.new({}, {}, env)
conf.clamp
assert_equal ['config/puma/fake-env.rb'], conf.config_files
end
def test_config_files_with_specified_environment
conf = Puma::Configuration.new do |c|
c.environment 'fake-env'
end
conf.clamp
assert_equal ['config/puma/fake-env.rb'], conf.config_files
end
def test_enable_keep_alives_by_default
conf = Puma::Configuration.new
conf.clamp
assert_equal conf.options[:enable_keep_alives], true
end
def test_enable_keep_alives_true
conf = Puma::Configuration.new do |c|
c.enable_keep_alives true
end
conf.clamp
assert_equal conf.options[:enable_keep_alives], true
end
def test_enable_keep_alives_false
conf = Puma::Configuration.new do |c|
c.enable_keep_alives false
end
conf.clamp
assert_equal conf.options[:enable_keep_alives], false
end
def test_on_booted_deprecated_alias_works
ran = false
conf = Puma::Configuration.new do |c|
c.on_booted { ran = true }
end
conf.clamp
conf.events.fire_after_booted!
assert ran, "on_booted callback should have run"
end
def test_on_restart_deprecated_alias_works
ran = false
conf = Puma::Configuration.new do |c|
c.on_restart { ran = true }
end
conf.clamp
conf.run_hooks(:before_restart, 'ARG', Puma::LogWriter.strings)
assert ran, "on_restart callback should have run"
end
def test_on_stopped_deprecated_alias_works
ran = false
conf = Puma::Configuration.new do |c|
c.on_stopped { ran = true }
end
conf.clamp
conf.events.fire_after_stopped!
assert ran, "on_stopped callback should have run"
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_example_cert_expiration.rb | test/test_example_cert_expiration.rb | # frozen_string_literal: true
require_relative 'helper'
require 'openssl'
#
# Thes are tests to ensure that the checked in certs in the ./examples/
# directory are valid and work as expected.
#
# These tests will start to fail 1 month before the certs expire
#
class TestExampleCertExpiration < PumaTest
EXAMPLES_DIR = File.expand_path '../examples/puma', __dir__
EXPIRE_THRESHOLD = Time.now.utc - (60 * 60 * 24 * 30) # 30 days
# Explicitly list the files to test
TEST_FILES = %w[
cert_puma.pem
client_certs/ca.crt
client_certs/client.crt
client_certs/client_unknown.crt
client_certs/server.crt
client_certs/unknown_ca.crt
chain_cert/ca.crt
chain_cert/cert.crt
chain_cert/intermediate.crt
]
def test_certs_not_expired
expiration_data = TEST_FILES.map do |path|
full_path = File.join(EXAMPLES_DIR, path)
not_after = OpenSSL::X509::Certificate.new(File.read(full_path)).not_after
[not_after, path]
end
failed = expiration_data.select { |ary| ary[0] <= EXPIRE_THRESHOLD }
if failed.empty?
assert true
else
msg = +"\n** The below certs in the 'examples/puma' folder are expiring soon.\n" \
" See 'examples/generate_all_certs.md' for instructions on how to regenerate.\n\n"
failed.each do |ary|
msg << " #{ary[1]}\n"
end
assert false, msg
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_log_writer.rb | test/test_log_writer.rb | require 'puma/detect'
require 'puma/log_writer'
require_relative "helper"
class TestLogWriter < PumaTest
def test_null
log_writer = Puma::LogWriter.null
assert_instance_of Puma::NullIO, log_writer.stdout
assert_instance_of Puma::NullIO, log_writer.stderr
assert_equal log_writer.stdout, log_writer.stderr
end
def test_strings
log_writer = Puma::LogWriter.strings
assert_instance_of StringIO, log_writer.stdout
assert_instance_of StringIO, log_writer.stderr
end
def test_stdio
log_writer = Puma::LogWriter.stdio
assert_equal STDOUT, log_writer.stdout
assert_equal STDERR, log_writer.stderr
end
def test_stdio_respects_sync
log_writer = Puma::LogWriter.stdio
assert_equal STDOUT.sync, log_writer.stdout.sync
assert_equal STDERR.sync, log_writer.stderr.sync
assert_equal STDOUT, log_writer.stdout
assert_equal STDERR, log_writer.stderr
end
def test_log_writes_to_stdout
out, _ = capture_io do
Puma::LogWriter.stdio.log("ready")
end
assert_equal "ready\n", out
end
def test_null_log_does_nothing
out, _ = capture_io do
Puma::LogWriter.null.log("ready")
end
assert_equal "", out
end
def test_write_writes_to_stdout
out, _ = capture_io do
Puma::LogWriter.stdio.write("ready")
end
assert_equal "ready", out
end
def test_debug_writes_to_stdout_if_env_is_present
original_debug, ENV["PUMA_DEBUG"] = ENV["PUMA_DEBUG"], "1"
out, _ = capture_io do
Puma::LogWriter.stdio.debug("ready")
end
assert_equal "% ready\n", out
ensure
ENV["PUMA_DEBUG"] = original_debug
end
def test_debug_not_write_to_stdout_if_env_is_not_present
out, _ = capture_io do
Puma::LogWriter.stdio.debug("ready")
end
assert_empty out
end
def test_error_writes_to_stderr_and_exits
did_exit = false
_, err = capture_io do
begin
Puma::LogWriter.stdio.error("interrupted")
rescue SystemExit
did_exit = true
ensure
assert did_exit
end
end
assert_match %r!ERROR: interrupted!, err
end
def test_pid_formatter
pid = Process.pid
out, _ = capture_io do
log_writer = Puma::LogWriter.stdio
log_writer.formatter = Puma::LogWriter::PidFormatter.new
log_writer.write("ready")
end
assert_equal "[#{ pid }] ready", out
end
def test_custom_log_formatter
custom_formatter = proc { |str| "-> #{ str }" }
out, _ = capture_io do
log_writer = Puma::LogWriter.stdio
log_writer.formatter = custom_formatter
log_writer.write("ready")
end
assert_equal "-> ready", out
end
def test_parse_error
app = proc { |_env| [200, {"Content-Type" => "plain/text"}, ["hello\n"]] }
log_writer = Puma::LogWriter.strings
server = Puma::Server.new app, nil, {log_writer: log_writer}
host = '127.0.0.1'
port = (server.add_tcp_listener host, 0).addr[1]
server.run
sock = TCPSocket.new host, port
path = "/"
params = "a"*1024*10
sock << "GET #{path}?a=#{params} HTTP/1.1\r\nConnection: close\r\n\r\n"
sock.read
sleep 0.1 # important so that the previous data is sent as a packet
assert_match %r!HTTP parse error, malformed request!, log_writer.stderr.string
assert_match %r!\("GET #{path}" - \(-\)\)!, log_writer.stderr.string
ensure
sock.close if sock && !sock.closed?
server&.stop(true)
end
# test_puma_server_ssl.rb checks that ssl errors are raised correctly,
# but it mocks the actual error code. This test the code, but it will
# break if the logged message changes
def test_ssl_error
log_writer = Puma::LogWriter.strings
ssl_mock = -> (addr, subj) {
obj = Object.new
obj.define_singleton_method(:peeraddr) { addr }
if subj
cert = Object.new
cert.define_singleton_method(:subject) { subj }
obj.define_singleton_method(:peercert) { cert }
else
obj.define_singleton_method(:peercert) { nil }
end
obj
}
log_writer.ssl_error OpenSSL::SSL::SSLError, ssl_mock.call(['127.0.0.1'], 'test_cert')
error = log_writer.stderr.string
assert_includes error, "SSL error"
assert_includes error, "peer: 127.0.0.1"
assert_includes error, "cert: test_cert"
log_writer.ssl_error OpenSSL::SSL::SSLError, ssl_mock.call(nil, nil)
error = log_writer.stderr.string.lines[1]
assert_includes error, "SSL error"
assert_includes error, "peer: <unknown>"
assert_includes error, "cert: :"
end if ::Puma::HAS_SSL
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_pumactl.rb | test/test_pumactl.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/ssl"
require 'pathname'
require 'puma/control_cli'
class TestPumaControlCli < PumaTest
include SSLHelper
def setup
# use a pipe to get info across thread boundary
@wait, @ready = IO.pipe
end
def wait_booted(log: nil)
@server_log = +''
begin
sleep 0.01 until @wait.wait_readable(0.01)
line = @wait.gets
STDOUT.syswrite "#{line}\n" if log
@server_log << line
end until line&.include?('Use Ctrl-C to stop')
end
def teardown
@wait.close
@ready.close unless @ready.closed?
end
def with_config_file(path_to_config, port)
path = Pathname.new(path_to_config)
Dir.mktmpdir do |tmp_dir|
Dir.chdir(tmp_dir) do
FileUtils.mkdir_p(path.dirname)
File.open(path, "w") { |f| f << "port #{port}" }
yield
end
end
end
def test_blank_command
assert_system_exit_with_cli_output [], "Available commands: #{Puma::ControlCLI::CMD_PATH_SIG_MAP.keys.join(", ")}"
end
def test_invalid_command
assert_system_exit_with_cli_output ['an-invalid-command'], 'Invalid command: an-invalid-command'
end
def test_config_file
control_cli = Puma::ControlCLI.new ["--config-file", "test/config/state_file_testing_config.rb", "halt"]
assert_equal "t3-pid", control_cli.instance_variable_get(:@pidfile)
ensure
File.unlink "t3-pid" if File.file? "t3-pid"
end
def test_app_env_without_environment
env = { 'APP_ENV' => 'test' }
control_cli = Puma::ControlCLI.new ['halt'], env: env
assert_equal 'test', control_cli.instance_variable_get(:@environment)
end
def test_rack_env_without_environment
env = { "RACK_ENV" => "test" }
control_cli = Puma::ControlCLI.new ["halt"], env: env
assert_equal "test", control_cli.instance_variable_get(:@environment)
end
def test_app_env_precedence
env = { 'APP_ENV' => nil, 'RACK_ENV' => nil, 'RAILS_ENV' => 'production' }
control_cli = Puma::ControlCLI.new ['halt'], env: env
assert_equal 'production', control_cli.instance_variable_get(:@environment)
env = { 'APP_ENV' => nil, 'RACK_ENV' => 'test', 'RAILS_ENV' => 'production' }
control_cli = Puma::ControlCLI.new ['halt'], env: env
assert_equal 'test', control_cli.instance_variable_get(:@environment)
env = { 'APP_ENV' => 'development', 'RACK_ENV' => 'test', 'RAILS_ENV' => 'production' }
control_cli = Puma::ControlCLI.new ['halt'], env: env
assert_equal 'development', control_cli.instance_variable_get(:@environment)
control_cli = Puma::ControlCLI.new ['-e', 'test', 'halt'], env: env
assert_equal 'test', control_cli.instance_variable_get(:@environment)
end
def test_environment_without_app_env
env = { 'APP_ENV' => nil, 'RACK_ENV' => nil, 'RAILS_ENV' => nil }
control_cli = Puma::ControlCLI.new ['halt'], env: env
assert_nil control_cli.instance_variable_get(:@environment)
control_cli = Puma::ControlCLI.new ['-e', 'test', 'halt'], env: env
assert_equal 'test', control_cli.instance_variable_get(:@environment)
end
def test_environment_without_rack_env
env = { "RACK_ENV" => nil, 'RAILS_ENV' => nil }
control_cli = Puma::ControlCLI.new ["halt"], env: env
assert_nil control_cli.instance_variable_get(:@environment)
control_cli = Puma::ControlCLI.new ["-e", "test", "halt"]
assert_equal "test", control_cli.instance_variable_get(:@environment)
end
def test_environment_with_rack_env
env = { "RACK_ENV" => "production" }
control_cli = Puma::ControlCLI.new ["halt"], env: env
assert_equal "production", control_cli.instance_variable_get(:@environment)
control_cli = Puma::ControlCLI.new ["-e", "test", "halt"], env: env
assert_equal "test", control_cli.instance_variable_get(:@environment)
end
def test_environment_specific_config_file_exist
port = UniquePort.call
puma_config_file = "config/puma.rb"
production_config_file = "config/puma/production.rb"
env = { "RACK_ENV" => nil }
with_config_file(puma_config_file, port) do
control_cli = Puma::ControlCLI.new ["-e", "production", "halt"], env: env
assert_equal puma_config_file, control_cli.instance_variable_get(:@config_file)
end
with_config_file(production_config_file, port) do
control_cli = Puma::ControlCLI.new ["-e", "production", "halt"], env: env
assert_equal production_config_file, control_cli.instance_variable_get(:@config_file)
end
end
def test_default_config_file_exist
port = UniquePort.call
puma_config_file = "config/puma.rb"
development_config_file = "config/puma/development.rb"
env = { "RACK_ENV" => nil, 'RAILS_ENV' => nil }
with_config_file(puma_config_file, port) do
control_cli = Puma::ControlCLI.new ["halt"], env: env
assert_equal puma_config_file, control_cli.instance_variable_get(:@config_file)
end
with_config_file(development_config_file, port) do
control_cli = Puma::ControlCLI.new ["halt"], env: env
assert_equal development_config_file, control_cli.instance_variable_get(:@config_file)
end
end
def test_control_no_token
opts = [
"--config-file", "test/config/control_no_token.rb",
"start"
]
control_cli = Puma::ControlCLI.new opts, @ready, @ready
assert_equal 'none', control_cli.instance_variable_get(:@control_auth_token)
end
def test_control_url_and_status
host = "127.0.0.1"
port = UniquePort.call
url = "tcp://#{host}:#{port}/"
opts = [
"--control-url", url,
"--control-token", "ctrl",
"--config-file", "test/config/app.rb"
]
control_cli = Puma::ControlCLI.new (opts + ["start"]), @ready, @ready
t = Thread.new do
control_cli.run
end
wait_booted # read server log
bind_port = @server_log[/Listening on http:.+:(\d+)$/, 1].to_i
s = TCPSocket.new host, bind_port
s << "GET / HTTP/1.0\r\n\r\n"
body = s.read
assert_includes body, "200 OK"
assert_includes body, "embedded app"
assert_command_cli_output opts + ["status"], "Puma is started"
assert_command_cli_output opts + ["stop"], "Command stop sent success"
assert_kind_of Thread, t.join, "server didn't stop"
end
# This checks that a 'signal only' command is sent
# they are defined by the `Puma::ControlCLI::NO_REQ_COMMANDS` array
# test is skipped unless NO_REQ_COMMANDS is defined
def test_control_url_with_signal_only_cmd
skip_if :windows
skip unless defined? Puma::ControlCLI::NO_REQ_COMMANDS
host = "127.0.0.1"
port = UniquePort.call
url = "tcp://#{host}:#{port}/"
opts = [
"--control-url", url,
"--control-token", "ctrl",
"--config-file", "test/config/app.rb",
"--pid", "1234"
]
cmd = Puma::ControlCLI::NO_REQ_COMMANDS.first
log = +''
control_cli = Puma::ControlCLI.new (opts + [cmd]), @ready, @ready
def control_cli.send_signal
message "send_signal #{@command}\n"
end
def control_cli.send_request
message "send_request #{@command}\n"
end
control_cli.run
@ready.close
log = @wait.read
assert_includes log, "send_signal #{cmd}"
refute_includes log, 'send_request'
end
def control_ssl(host)
skip_unless :ssl
ip = host&.start_with?('[') ? host[1..-2] : host
port = UniquePort.call(ip)
url = "ssl://#{host}:#{port}?#{ssl_query}"
opts = [
"--control-url", url,
"--control-token", "ctrl",
"--config-file", "test/config/app.rb"
]
control_cli = Puma::ControlCLI.new (opts + ["start"]), @ready, @ready
t = Thread.new do
control_cli.run
end
wait_booted
assert_command_cli_output opts + ["status"], "Puma is started"
assert_command_cli_output opts + ["stop"], "Command stop sent success"
assert_kind_of Thread, t.join, "server didn't stop"
end
def test_control_ssl_ipv4
skip_unless :ssl
control_ssl '127.0.0.1'
end
def test_control_ssl_ipv6
skip_unless :ssl
control_ssl '[::1]'
end
def test_control_aunix
skip_unless :aunix
url = "unix://@test_control_aunix.unix"
opts = [
"--control-url", url,
"--control-token", "ctrl",
"--config-file", "test/config/app.rb"
]
control_cli = Puma::ControlCLI.new (opts + ["start"]), @ready, @ready
t = Thread.new do
control_cli.run
end
wait_booted
assert_command_cli_output opts + ["status"], "Puma is started"
assert_command_cli_output opts + ["stop"], "Command stop sent success"
assert_kind_of Thread, t.join, "server didn't stop"
end
def test_control_ipv6
port = UniquePort.call '::1'
url = "tcp://[::1]:#{port}"
opts = [
"--control-url", url,
"--control-token", "ctrl",
"--config-file", "test/config/app.rb"
]
control_cli = Puma::ControlCLI.new (opts + ["start"]), @ready, @ready
t = Thread.new do
control_cli.run
end
wait_booted
assert_command_cli_output opts + ["status"], "Puma is started"
assert_command_cli_output opts + ["stop"], "Command stop sent success"
assert_kind_of Thread, t.join, "server didn't stop"
end
private
def assert_command_cli_output(options, expected_out)
@rd, @wr = IO.pipe
cmd = Puma::ControlCLI.new(options, @wr, @wr)
begin
cmd.run
rescue SystemExit
end
@wr.close
if String === expected_out
assert_includes @rd.read, expected_out
else
assert_match expected_out, @rd.read
end
ensure
@rd.close
end
def assert_system_exit_with_cli_output(options, expected_out)
@rd, @wr = IO.pipe
response = assert_raises(SystemExit) do
Puma::ControlCLI.new(options, @wr, @wr).run
end
@wr.close
assert_equal(response.status, 1)
if String === expected_out
assert_includes @rd.read, expected_out
else
assert_match expected_out, @rd.read
end
ensure
@rd.close
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_puma_server_hijack.rb | test/test_puma_server_hijack.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/test_puma/puma_socket"
require "puma/events"
require "puma/server"
require "net/http"
require "nio"
require "rack"
require "rack/body_proxy"
# Tests check both the proper passing of the socket to the app, and also calling
# of `body.close` on the response body. Rack spec is unclear as to whether
# calling close is expected.
#
# The sleep statements may not be needed for local CI, but are needed
# for use with GitHub Actions...
class TestPumaServerHijack < PumaTest
parallelize_me!
include TestPuma
include TestPuma::PumaSocket
HOST = HOST4
def setup
@host = HOST
@ios = []
@app = ->(env) { [200, {}, [env['rack.url_scheme']]] }
@log_writer = Puma::LogWriter.strings
@events = Puma::Events.new
end
def teardown
return if skipped?
@server.stop(true)
assert_empty @log_writer.stdout.string
assert_empty @log_writer.stderr.string
end
def server_run(**options, &block)
options[:log_writer] ||= @log_writer
options[:min_threads] ||= 1
@server = Puma::Server.new block || @app, @events, options
@bind_port = (@server.add_tcp_listener @host, 0).addr[1]
@server.run
end
# Full hijack does not return headers
def test_full_hijack_body_close
@body_closed = false
server_run do |env|
io = env['rack.hijack'].call
io.syswrite 'Server listening'
io.wait_readable 2
io.syswrite io.sysread(256)
body = ::Rack::BodyProxy.new([]) { @body_closed = true }
[200, {}, body]
end
sock = send_http "GET / HTTP/1.1\r\n\r\n"
sock.wait_readable 2
assert_equal "Server listening", sock.sysread(256)
sock.syswrite "this should echo"
assert_equal "this should echo", sock.sysread(256)
Thread.pass
sleep 0.001 # intermittent failure, may need to increase in CI
assert @body_closed, "Reponse body must be closed"
end
def test_101_body
headers = {
'Upgrade' => 'websocket',
'Connection' => 'Upgrade',
'Sec-WebSocket-Accept' => 's3pPLMBiTxaQ9kYGzzhZRbK+xOo=',
'Sec-WebSocket-Protocol' => 'chat'
}
body = -> (io) {
# below for TruffleRuby error with io.sysread
# Read Errno::EAGAIN: Resource temporarily unavailable
io.wait_readable 0.1
io.syswrite io.sysread(256)
io.close
}
server_run do |env|
[101, headers, body]
end
sock = send_http "GET / HTTP/1.1\r\n\r\n"
response = sock.read_response
echo_msg = "This should echo..."
sock.syswrite echo_msg
assert_includes response, 'connection: Upgrade'
sock.wait_readable 0.2 # for TruffleRuby Errno::EAGAIN
assert_equal echo_msg, sock.sysread(256)
end
def test_101_header
headers = {
'Upgrade' => 'websocket',
'Connection' => 'Upgrade',
'Sec-WebSocket-Accept' => 's3pPLMBiTxaQ9kYGzzhZRbK+xOo=',
'Sec-WebSocket-Protocol' => 'chat',
'rack.hijack' => -> (io) {
# below for TruffleRuby error with io.sysread
# Read Errno::EAGAIN: Resource temporarily unavailable
io.wait_readable 0.1
io.syswrite io.sysread(256)
io.close
}
}
server_run do |env|
[101, headers, []]
end
sock = send_http "GET / HTTP/1.1\r\n\r\n"
response = sock.read_response
echo_msg = "This should echo..."
sock.syswrite echo_msg
assert_includes response, 'connection: Upgrade'
sock.wait_readable 0.2 # for TruffleRuby Errno::EAGAIN
assert_equal echo_msg, sock.sysread(256)
end
def test_http_10_header_with_content_length
body_parts = ['abc', 'de']
server_run do
hijack_lambda = proc do | io |
io.write(body_parts[0])
io.write(body_parts[1])
io.close
end
[200, {"Content-Length" => "5", 'rack.hijack' => hijack_lambda}, nil]
end
# using sysread may only receive part of the response
response = send_http_read_response "GET / HTTP/1.0\r\nConnection: close\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\ncontent-length: 5\r\n\r\nabcde", response
end
def test_partial_hijack_body_closes_body
skip 'Not supported with Rack 1.x' if Rack.release.start_with? '1.'
@available = true
hdrs = { 'Content-Type' => 'text/plain' }
body = ::Rack::BodyProxy.new(HIJACK_LAMBDA) { @available = true }
partial_hijack_closes_body(hdrs, body)
end
def test_partial_hijack_header_closes_body_correct_precedence
skip 'Not supported with Rack 1.x' if Rack.release.start_with? '1.'
@available = true
incorrect_lambda = ->(io) {
io.syswrite 'incorrect body.call'
io.close
}
hdrs = { 'Content-Type' => 'text/plain', 'rack.hijack' => HIJACK_LAMBDA}
body = ::Rack::BodyProxy.new(incorrect_lambda) { @available = true }
partial_hijack_closes_body(hdrs, body)
end
HIJACK_LAMBDA = ->(io) {
io.syswrite 'hijacked'
io.close
}
def partial_hijack_closes_body(hdrs, body)
server_run do
if @available
@available = false
[200, hdrs, body]
else
[500, { 'Content-Type' => 'text/plain' }, ['incorrect']]
end
end
sock1 = send_http "GET / HTTP/1.1\r\n\r\n"
sleep (Puma::IS_WINDOWS || !Puma::IS_MRI ? 0.3 : 0.1)
response1 = sock1.read_response
sleep 0.01 # time for close block to be called ?
sock2 = send_http "GET / HTTP/1.1\r\n\r\n"
sleep (Puma::IS_WINDOWS || !Puma::IS_MRI ? 0.3 : 0.1)
response2 = sock2.read_response
assert_operator response1, :end_with?, 'hijacked'
assert_operator response2, :end_with?, 'hijacked'
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_puma_server.rb | test/test_puma_server.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/test_puma/puma_socket"
require "puma/events"
require "puma/server"
require "nio"
require "ipaddr"
class WithoutBacktraceError < StandardError
def backtrace; nil; end
def message; "no backtrace error"; end
end
class TestPumaServer < PumaTest
parallelize_me!
include TestPuma
include TestPuma::PumaSocket
STATUS_CODES = ::Puma::HTTP_STATUS_CODES
HOST = HOST4
def setup
@host = HOST
@app = ->(env) { [200, {}, [env['rack.url_scheme']]] }
@log_writer = Puma::LogWriter.strings
@events = Puma::Events.new
@server = Puma::Server.new @app, @events, {log_writer: @log_writer}
end
def teardown
@server.stop(true)
# Errno::EBADF raised on macOS
end
def server_run(**options, &block)
options[:log_writer] ||= @log_writer
options[:min_threads] ||= 1
@server = Puma::Server.new block || @app, @events, options
@bind_port = (@server.add_tcp_listener @host, 0).addr[1]
@server.run
ensure
@pool = @server.instance_variable_get(:@thread_pool)
end
def test_http10_req_to_http10_resp
server_run do |env|
[200, {}, [env["SERVER_PROTOCOL"]]]
end
response = send_http_read_response GET_10
assert_equal "HTTP/1.0 200 OK", response.status
assert_equal "HTTP/1.0" , response.body
end
def test_http11_req_to_http11_resp
server_run do |env|
[200, {}, [env["SERVER_PROTOCOL"]]]
end
response = send_http_read_response GET_11
assert_equal "HTTP/1.1 200 OK", response.status
assert_equal "HTTP/1.1" , response.body
end
def test_normalize_host_header_missing
server_run do |env|
[200, {}, [env["SERVER_NAME"], "\n", env["SERVER_PORT"]]]
end
body = send_http_read_resp_body GET_10
assert_equal "localhost\n80", body
end
def test_normalize_host_header_hostname
server_run do |env|
[200, {}, [env["SERVER_NAME"], "\n", env["SERVER_PORT"]]]
end
body = send_http_read_resp_body "GET / HTTP/1.0\r\nHost: example.com:456\r\n\r\n"
assert_equal "example.com\n456", body
body = send_http_read_resp_body "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n"
assert_equal "example.com\n80", body
end
def test_normalize_host_header_ipv4
server_run do |env|
[200, {}, [env["SERVER_NAME"], "\n", env["SERVER_PORT"]]]
end
body = send_http_read_resp_body "GET / HTTP/1.0\r\nHost: 123.123.123.123:456\r\n\r\n"
assert_equal "123.123.123.123\n456", body
body = send_http_read_resp_body "GET / HTTP/1.0\r\nHost: 123.123.123.123\r\n\r\n"
assert_equal "123.123.123.123\n80", body
end
def test_normalize_host_header_ipv6
server_run do |env|
[200, {}, [env["SERVER_NAME"], "\n", env["SERVER_PORT"]]]
end
body = send_http_read_resp_body "GET / HTTP/1.0\r\nHost: [::ffff:127.0.0.1]:9292\r\n\r\n"
assert_equal "[::ffff:127.0.0.1]\n9292", body
body = send_http_read_resp_body "GET / HTTP/1.0\r\nHost: [::1]:9292\r\n\r\n"
assert_equal "[::1]\n9292", body
body = send_http_read_resp_body "GET / HTTP/1.0\r\nHost: [::1]\r\n\r\n"
assert_equal "[::1]\n80", body
end
def test_streaming_body
server_run do |env|
body = lambda do |stream|
stream.write("Hello World")
stream.close
end
[200, {}, body]
end
body = send_http_read_resp_body "GET / HTTP/1.0\r\nConnection: close\r\n\r\n"
assert_equal "Hello World", body
end
def test_file_body
random_bytes = SecureRandom.random_bytes(4096 * 32)
tf = tempfile_create("test_file_body", random_bytes)
server_run { |env| [200, {}, tf] }
body = send_http_read_resp_body "GET / HTTP/1.1\r\nHost: [::ffff:127.0.0.1]:#{@bind_port}\r\n\r\n"
assert_equal random_bytes.bytesize, body.bytesize
assert_equal random_bytes, body
ensure
tf&.close
end
def test_file_to_path
random_bytes = SecureRandom.random_bytes(4096 * 32)
tf = tempfile_create("test_file_to_path", random_bytes)
path = tf.path
obj = Object.new
obj.singleton_class.send(:define_method, :to_path) { path }
obj.singleton_class.send(:define_method, :each) { path } # dummy, method needs to exist
server_run { |env| [200, {}, obj] }
body = send_http_read_resp_body
assert_equal random_bytes.bytesize, body.bytesize
assert_equal random_bytes, body
ensure
tf&.close
end
def test_pipe_body_http11
random_bytes = SecureRandom.random_bytes(4096)
r, w = IO.pipe(binmode: true)
w.write random_bytes
w.close
server_run { |env| [200, {}, r] }
response = send_http_read_response
body = response.decode_body
assert_equal random_bytes.bytesize, body.bytesize
assert_equal random_bytes, body
ensure
w&.close
r&.close
end
def test_pipe_body_http10
bytes = 4_096
random_bytes = SecureRandom.random_bytes(bytes)
r, w = IO.pipe(binmode: true)
w.write random_bytes
w.close
server_run { |env| [200, {'content-length' => bytes.to_s}, r] }
response = send_http_read_response GET_10
body = response.body
assert_equal random_bytes.bytesize, body.bytesize
assert_equal random_bytes, body
ensure
w&.close
r&.close
end
# Older Rubies may only read 16k, maybe OS dependent
def test_request_body_small
data = nil
server_run do |env|
data = env['rack.input'].read
[200, {}, [env['rack.input'].to_s]]
end
small_body = 'x' * 15 * 1_024
small_body_bytes = small_body.bytesize
socket = send_http "PUT / HTTP/1.0\r\n" \
"Content-Length: #{small_body_bytes}\r\n\r\n" \
"#{small_body}"
assert_includes socket.read_response, 'StringIO'
assert_equal small_body_bytes, data.bytesize
assert_equal small_body, data
# below intermitttently fails on GitHub Actions, may work locally
# assert_equal 0, @server.stats[:reactor_max]
end
def test_request_body_large
data = nil
server_run do |env|
data = env['rack.input'].read
[200, {}, [env['rack.input'].to_s]]
end
large_body = 'x' * 70 * 1_024
large_body_bytes = large_body.bytesize
socket = send_http "PUT / HTTP/1.0\r\n" \
"Content-Length: #{large_body_bytes}\r\n\r\n" \
"#{large_body}"
assert_includes socket.read_response, 'StringIO'
assert_equal large_body_bytes, data.bytesize
assert_equal large_body, data
# below intermitttently fails on GitHub Actions, may work locally
# assert_equal 0, @server.stats[:reactor_max]
end
def test_proper_stringio_body
data = nil
server_run do |env|
data = env['rack.input'].read
[200, {}, [env['rack.input'].to_s]]
end
fifteen = "1" * 15
socket = send_http "PUT / HTTP/1.0\r\nContent-Length: 30\r\n\r\n#{fifteen}"
sleep 0.1 # important so that the previous data is sent as a packet
socket << fifteen
assert_includes socket.read_response, 'StringIO'
assert_equal "#{fifteen}#{fifteen}", data
end
def test_puma_socket
body = "HTTP/1.1 750 Upgraded to Awesome\r\nDone: Yep!\r\n"
server_run do |env|
io = env['puma.socket']
io.write body
io.close
[-1, {}, []]
end
data = send_http_read_response "PUT / HTTP/1.0\r\n\r\nHello"
assert_equal body, data
end
def test_very_large_return
giant = "x" * 2056610
server_run do
[200, {}, [giant]]
end
body = send_http_read_resp_body GET_10
assert_equal giant.bytesize, body.bytesize
end
def test_respect_x_forwarded_proto
env = {}
env['HOST'] = "example.com"
env['HTTP_X_FORWARDED_PROTO'] = "https,http"
assert_equal "443", @server.default_server_port(env)
end
def test_respect_x_forwarded_ssl_on
env = {}
env['HOST'] = 'example.com'
env['HTTP_X_FORWARDED_SSL'] = 'on'
assert_equal "443", @server.default_server_port(env)
end
def test_respect_x_forwarded_scheme
env = {}
env['HOST'] = 'example.com'
env['HTTP_X_FORWARDED_SCHEME'] = 'https'
assert_equal '443', @server.default_server_port(env)
end
def test_default_server_port
server_run do |env|
[200, {}, [env['SERVER_PORT']]]
end
req = "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n"
body = send_http_read_resp_body req
assert_equal "80", body
end
def test_default_server_port_respects_x_forwarded_proto
server_run do |env|
[200, {}, [env['SERVER_PORT']]]
end
req = "GET / HTTP/1.0\r\nHost: example.com\r\nx-forwarded-proto: https,http\r\n\r\n"
body = send_http_read_resp_body req
assert_equal "443", body
end
def test_HEAD_has_no_body
server_run { [200, {"Foo" => "Bar"}, ["hello"]] }
response = send_http_read_response "HEAD / HTTP/1.0\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\nfoo: Bar\r\ncontent-length: 5\r\n\r\n", response
end
def test_GET_with_empty_body_has_sane_chunking
server_run { [200, {}, [""]] }
response = send_http_read_response "HEAD / HTTP/1.0\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\ncontent-length: 0\r\n\r\n", response
end
def test_back_to_back_no_content
bodies = []
server_run { |e|
bodies << e['rack.input'].read
[200, {}, ["ok #{bodies.size}"]]
}
data = send_http_read_all(
"GET / HTTP/1.1\r\nHost: a\r\nContent-Length: 0\r\n\r\n" \
"GET / HTTP/1.1\r\nConnection: close\r\n\r\n"
)
assert_equal(
"HTTP/1.1 200 OK\r\ncontent-length: 4\r\n\r\nok 1" \
"HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: 4\r\n\r\nok 2", data
)
assert_equal ["", ""], bodies
end
def test_back_to_back_content
bodies = []
server_run { |e|
bodies << e['rack.input'].read
[200, {}, ["ok #{bodies.size}"]]
}
data = send_http_read_all(
"GET / HTTP/1.1\r\nHost: a\r\nContent-Length: 1\r\n\r\na" \
"GET / HTTP/1.1\r\nContent-Length: 0\r\n\r\n"
)
assert_equal(
"HTTP/1.1 200 OK\r\ncontent-length: 4\r\n\r\nok 1" \
"HTTP/1.1 200 OK\r\ncontent-length: 4\r\n\r\nok 2", data
)
assert_equal ["a", ""], bodies
end
def test_back_to_back_chunked
server_run { |env|
[200, {'Content-Length' => env['CONTENT_LENGTH']}, [env['rack.input'].read]]
}
socket = send_http(
"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nh\r\n4\r\nello\r\n0\r\n\r\n" \
"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ngood\r\n3\r\nbye\r\n0\r\n\r\n"
)
sleep 0.05 # let both requests be processed?
data = socket.sysread 1_024
assert_equal(
"HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nhello" \
"HTTP/1.1 200 OK\r\ncontent-length: 7\r\n\r\ngoodbye", data
)
socket << "GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nH\r\n4\r\nello\r\n0\r\n\r\n"
response = socket.read_response
assert_equal "HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nHello", response
end
def test_early_hints_works
server_run(early_hints: true) do |env|
env['rack.early_hints'].call("Link" => "</style.css>; rel=preload; as=style\n</script.js>; rel=preload")
[200, { "X-Hello" => "World" }, ["Hello world!"]]
end
# two requests must be read
response = send_http_read_all "HEAD / HTTP/1.0\r\n\r\n"
expected_resp = <<~EOF.gsub("\n", "\r\n") + "\r\n"
HTTP/1.1 103 Early Hints
Link: </style.css>; rel=preload; as=style
Link: </script.js>; rel=preload
HTTP/1.0 200 OK
x-hello: World
content-length: 12
EOF
assert_equal true, @server.early_hints
assert_equal expected_resp, response
end
def test_early_hints_are_ignored_if_connection_lost
server_run(early_hints: true) do |env|
env['rack.early_hints'].call("Link" => "</script.js>; rel=preload")
[200, { "X-Hello" => "World" }, ["Hello world!"]]
end
def @server.fast_write(*args)
raise Puma::ConnectionError
end
# This request will cause the server to try and send early hints
_ = send_http "HEAD / HTTP/1.0\r\n\r\n"
# Give the server some time to try to write (and fail)
sleep 0.1
# Expect no errors in stderr
assert @log_writer.stderr.pos.zero?, "Server didn't swallow the connection error"
end
def test_early_hints_is_off_by_default
server_run do |env|
assert_nil env['rack.early_hints']
[200, { "X-Hello" => "World" }, ["Hello world!"]]
end
response = send_http_read_response "HEAD / HTTP/1.0\r\n\r\n"
expected_resp = <<~EOF.gsub("\n", "\r\n") + "\r\n"
HTTP/1.0 200 OK
x-hello: World
content-length: 12
EOF
assert_nil @server.early_hints
assert_equal expected_resp, response
end
def test_request_payload_too_large
server_run(http_content_length_limit: 10)
socket = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 19\r\n\r\n"
socket << "hello world foo bar"
response = socket.read_response
# Content Too Large
assert_equal "HTTP/1.1 413 #{STATUS_CODES[413]}", response.status
end
def test_http_11_keep_alive_with_large_payload
server_run(http_content_length_limit: 10) { [204, {}, []] }
socket = send_http "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\nContent-Length: 17\r\n\r\n"
socket << "hello world foo bar"
response = socket.read_response
# Content Too Large
assert_equal "HTTP/1.1 413 #{STATUS_CODES[413]}", response.status
assert_equal ["content-length: 17"], response.headers
end
def test_GET_with_no_body_has_sane_chunking
server_run { [200, {}, []] }
response = send_http_read_response "HEAD / HTTP/1.0\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\ncontent-length: 0\r\n\r\n", response
end
def test_doesnt_print_backtrace_in_production
server_run(environment: :production) { raise "don't leak me bro" }
response = send_http_read_response GET_10
refute_match(/don't leak me bro/, response)
assert_equal 'HTTP/1.0 500 Internal Server Error', response.status
end
def test_eof_on_connection_close_is_not_logged_as_an_error
server_run
new_socket.close # Make a connection and close without writing
@server.stop(true)
stderr = @log_writer.stderr.string
assert stderr.empty?, "Expected stderr from server to be empty but it was #{stderr.inspect}"
end
def test_force_shutdown_custom_error_message
handler = lambda {|err, env, status| [500, {"Content-Type" => "application/json"}, ["{}\n"]]}
server_run(lowlevel_error_handler: handler, force_shutdown_after: 2) do
@server.stop
sleep 5
end
response = send_http_read_response GET_10
assert_equal 'HTTP/1.0 500 Internal Server Error', response.status
assert_match(/content-type: application\/json/, response)
assert_match(/{}\n$/, response)
end
class ArrayClose < Array
attr_reader :is_closed
def closed?
@is_closed
end
def close
@is_closed = true
end
end
# returns status as an array, which throws lowlevel error
def test_lowlevel_error_body_close
app_body = ArrayClose.new(['lowlevel_error'])
server_run(log_writer: @log_writer, :force_shutdown_after => 2) do
[[0,1], {}, app_body]
end
response = send_http_read_response "GET / HTTP/1.0\r\n\r\n"
assert_start_with response, 'HTTP/1.0 500 Internal Server Error'
assert_match(/Puma caught this error: undefined method [`']to_i' for/, response)
assert_includes response, "Array"
refute_includes response, 'lowlevel_error'
sleep 0.1 unless ::Puma::IS_MRI
assert app_body.closed?
end
def test_lowlevel_error_message
server_run(log_writer: @log_writer, :force_shutdown_after => 2) do
raise NoMethodError, "Oh no an error"
end
response = send_http_read_response GET_10
# Internal Server Error
assert_equal "HTTP/1.0 500 #{STATUS_CODES[500]}", response.status
assert_match(/Puma caught this error: Oh no an error.*\(NoMethodError\).*test\/test_puma_server.rb/m, response)
end
def test_lowlevel_error_message_without_backtrace
server_run(log_writer: @log_writer, :force_shutdown_after => 2) do
raise WithoutBacktraceError.new
end
response = send_http_read_response GET_11
# Internal Server Error
assert_equal "HTTP/1.1 500 #{STATUS_CODES[500]}", response.status
assert_includes response, 'Puma caught this error: no backtrace error (WithoutBacktraceError)'
assert_includes response, '<no backtrace available>'
end
def test_force_shutdown_error_default
server_run(force_shutdown_after: 2) do
@server.stop
sleep 5
end
response = send_http_read_response GET_10
assert_equal 'HTTP/1.0 503 Service Unavailable', response.status
assert_match(/Puma caught this error.+Puma::ThreadPool::ForceShutdown/, response)
end
def test_prints_custom_error
re = lambda { |err| [302, {'Content-Type' => 'text', 'Location' => 'foo.html'}, ['302 found']] }
server_run(lowlevel_error_handler: re) { raise "don't leak me bro" }
response = send_http_read_response GET_10
assert_equal 'HTTP/1.0 302 Found', response.status
end
def test_leh_gets_env_as_well
re = lambda { |err,env|
env['REQUEST_PATH'] || raise('where is env?')
[302, {'Content-Type' => 'text', 'Location' => 'foo.html'}, ['302 found']]
}
server_run(lowlevel_error_handler: re) { raise "don't leak me bro" }
response = send_http_read_response GET_10
assert_equal 'HTTP/1.0 302 Found', response.status
end
def test_leh_has_status
re = lambda { |err, env, status|
raise "Cannot find status" unless status
[302, {'Content-Type' => 'text', 'Location' => 'foo.html'}, ['302 found']]
}
server_run(lowlevel_error_handler: re) { raise "don't leak me bro" }
response = send_http_read_response GET_10
assert_equal 'HTTP/1.0 302 Found', response.status
end
def test_custom_http_codes_10
server_run { [449, {}, [""]] }
response = send_http_read_response GET_10
assert_equal "HTTP/1.0 449 CUSTOM\r\ncontent-length: 0\r\n\r\n", response
end
def test_custom_http_codes_11
server_run { [449, {}, [""]] }
response = send_http_read_response "GET / HTTP/1.1\r\nConnection: close\r\n\r\n"
assert_equal "HTTP/1.1 449 CUSTOM\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", response
end
def test_HEAD_returns_content_headers
server_run { [200, {"Content-Type" => "application/pdf",
"Content-Length" => "4242"}, []] }
response = send_http_read_response "HEAD / HTTP/1.0\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\ncontent-type: application/pdf\r\ncontent-length: 4242\r\n\r\n", response
end
def test_status_hook_fires_when_server_changes_states
states = []
@events.register(:state) { |s| states << s }
server_run { [200, {}, [""]] }
_ = send_http_read_response "HEAD / HTTP/1.0\r\n\r\n"
assert_equal [:booting, :running], states
@server.stop(true)
assert_equal [:booting, :running, :stop, :done], states
end
def test_timeout_in_data_phase(**options)
server_run(first_data_timeout: 1, **options)
socket = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\n"
socket << "Hello" unless socket.wait_readable(1.15)
response = socket.read_response
# Request Timeout
assert_equal "HTTP/1.1 408 #{STATUS_CODES[408]}", response.status
end
def test_timeout_data_no_queue
test_timeout_in_data_phase(queue_requests: false)
end
# https://github.com/puma/puma/issues/2574
def test_no_timeout_after_data_received
@server.instance_variable_set(:@first_data_timeout, 1)
server_run
socket = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 11\r\n\r\n"
sleep 0.5
socket << "hello"
sleep 0.5
socket << "world"
sleep 0.5
socket << "!"
response = socket.read_response
assert_equal "HTTP/1.1 200 OK", response.status
end
def test_no_timeout_after_data_received_no_queue
@server = Puma::Server.new @app, @events, {log_writer: @log_writer, queue_requests: false}
test_no_timeout_after_data_received
end
def test_idle_timeout_before_first_request
server_run(idle_timeout: 1)
sleep 1.15
assert @server.shutting_down?
assert_raises Errno::ECONNREFUSED do
send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\n"
end
end
def test_idle_timeout_before_first_request_data
server_run(idle_timeout: 1)
socket = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\n"
sleep 1.15
socket << "hello world!"
response = socket.read_response
assert_equal "HTTP/1.1 200 OK", response.status
end
def test_idle_timeout_between_first_request_data
server_run(idle_timeout: 1)
socket = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\n"
socket << "hello"
sleep 1.15
socket << " world!"
response = socket.read_response
assert_equal "HTTP/1.1 200 OK", response.status
end
def test_idle_timeout_after_first_request
server_run(idle_timeout: 1)
socket = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\n"
socket << "hello world!"
response = socket.read_response
assert_equal "HTTP/1.1 200 OK", response.status
sleep 1.15
assert @server.shutting_down?
assert socket.wait_readable(1), 'Unexpected timeout'
assert_raises Errno::ECONNREFUSED do
send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\n"
end
end
def test_idle_timeout_between_request_data
server_run(idle_timeout: 1)
socket = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\n"
socket << "hello world!"
response = socket.read_response
assert_equal "HTTP/1.1 200 OK", response.status
sleep 0.5
socket = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\n"
socket << "hello"
sleep 1.15
socket << " world!"
response = socket.read_response
assert_equal "HTTP/1.1 200 OK", response.status
sleep 1.15
assert @server.shutting_down?
assert socket.wait_readable(1), 'Unexpected timeout'
assert_raises Errno::ECONNREFUSED do
send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\n"
end
end
def test_idle_timeout_between_requests
server_run(idle_timeout: 1)
socket = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\n"
socket << "hello world!"
response = socket.read_response
assert_equal "HTTP/1.1 200 OK", response.status
sleep 0.5
socket = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\n"
socket << "hello world!"
response = socket.read_response
assert_equal "HTTP/1.1 200 OK", response.status
sleep 1.15
assert @server.shutting_down?
assert socket.wait_readable(1), 'Unexpected timeout'
assert_raises Errno::ECONNREFUSED do
send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\n"
end
end
def test_http_11_keep_alive_with_body
server_run { [200, {"Content-Type" => "plain/text"}, ["hello\n"]] }
req = "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\n\r\n"
response = send_http_read_response req
assert_equal ["content-type: plain/text", "content-length: 6"], response.headers
assert_equal "hello\n", response.body
end
def test_http_11_close_with_body
server_run { [200, {"Content-Type" => "plain/text"}, ["hello"]] }
response = send_http_read_response "GET / HTTP/1.1\r\nConnection: close\r\n\r\n"
assert_equal "HTTP/1.1 200 OK\r\ncontent-type: plain/text\r\nconnection: close\r\ncontent-length: 5\r\n\r\nhello", response
end
def test_http_11_keep_alive_without_body
server_run { [204, {}, []] }
response = send_http_read_response "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\n\r\n"
# No Content
assert_equal "HTTP/1.1 204 #{STATUS_CODES[204]}", response.status
end
def test_http_11_close_without_body
server_run { [204, {}, []] }
req = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n"
response = send_http_read_response req
# No Content
assert_equal "HTTP/1.1 204 #{STATUS_CODES[204]}", response.status
assert_equal ["connection: close"], response.headers
end
def test_http_11_enable_keep_alives_by_default
server_run(enable_keep_alives: true) { [200, {"Content-Type" => "plain/text"}, ["hello\n"]] }
req = "GET / HTTP/1.1\r\n\r\n"
response = send_http_read_response req
# No "connection: close" header.
assert_equal ["content-type: plain/text", "content-length: 6"], response.headers
assert_equal "hello\n", response.body
end
def test_http_11_enable_keep_alives_true
server_run(enable_keep_alives: true) { [200, {"Content-Type" => "plain/text"}, ["hello\n"]] }
req = "GET / HTTP/1.1\r\n\r\n"
response = send_http_read_response req
# No "connection: close" header.
assert_equal ["content-type: plain/text", "content-length: 6"], response.headers
assert_equal "hello\n", response.body
end
def test_http_11_enable_keep_alives_false
server_run(enable_keep_alives: false) { [200, {"Content-Type" => "plain/text"}, ["hello\n"]] }
req = "GET / HTTP/1.1\r\n\r\n"
response = send_http_read_response req
# Assert the "connection: close" header is present with keep-alives disabled.
assert_equal ["content-type: plain/text", "connection: close", "content-length: 6"], response.headers
assert_equal "hello\n", response.body
end
def test_http_10_keep_alive_with_body
server_run { [200, {"Content-Type" => "plain/text"}, ["hello\n"]] }
req = "GET / HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n"
response = send_http_read_response req
assert_equal "HTTP/1.0 200 OK", response.status
assert_equal ["content-type: plain/text", "connection: keep-alive", "content-length: 6"],
response.headers
assert_equal "hello\n", response.body
end
def test_http_10_close_with_body
server_run { [200, {"Content-Type" => "plain/text"}, ["hello"]] }
response = send_http_read_response "GET / HTTP/1.0\r\nConnection: close\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\ncontent-type: plain/text\r\ncontent-length: 5\r\n\r\nhello", response
end
def test_http_10_keep_alive_without_body
server_run { [204, {}, []] }
response = send_http_read_response "GET / HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n"
assert_equal "HTTP/1.0 204 No Content\r\nconnection: keep-alive\r\n\r\n", response
end
def test_http_10_close_without_body
server_run { [204, {}, []] }
response = send_http_read_response "GET / HTTP/1.0\r\nConnection: close\r\n\r\n"
assert_equal "HTTP/1.0 204 No Content\r\n\r\n", response
end
def test_Expect_100
server_run { [200, {}, [""]] }
# two requests must be read
response = send_http_read_all "GET / HTTP/1.1\r\nConnection: close\r\nExpect: 100-continue\r\n\r\n"
assert_equal "HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", response
end
def test_chunked_request
body = nil
content_length = nil
transfer_encoding = nil
server_run { |env|
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
transfer_encoding = env['HTTP_TRANSFER_ENCODING']
[200, {}, [""]]
}
response = send_http_read_response "GET / HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: gzip,chunked\r\n\r\n1\r\nh\r\n4\r\nello\r\n0\r\n\r\n"
assert_equal "HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", response
assert_equal "hello", body
assert_equal "5", content_length
assert_nil transfer_encoding
end
# See also test_chunked_keep_alive_two_back_to_back
def test_two_back_to_back_chunked_have_different_tempfile
body = nil
content_length = nil
transfer_encoding = nil
req_body_path = nil
server_run { |env|
io = env['rack.input']
req_body_path = io.path
body = io.read
content_length = env['CONTENT_LENGTH']
transfer_encoding = env['HTTP_TRANSFER_ENCODING']
[200, {}, [""]]
}
chunked_req = "GET / HTTP/1.1\r\nTransfer-Encoding: gzip,chunked\r\n\r\n1\r\nh\r\n4\r\nello\r\n0\r\n\r\n"
skt = send_http chunked_req
response = skt.read_response
path1 = req_body_path
assert_equal "HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n", response
assert_equal "hello", body
assert_equal "5", content_length
assert_nil transfer_encoding
skt << chunked_req
response = skt.read_response
path2 = req_body_path
# same as above
assert_equal "HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n", response
assert_equal "hello", body
assert_equal "5", content_length
assert_nil transfer_encoding
refute_equal path1, path2
end
def test_large_chunked_request
body = nil
content_length = nil
server_run { |env|
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
header = "GET / HTTP/1.1\r\nConnection: close\r\nContent-Length: 200\r\nTransfer-Encoding: chunked\r\n\r\n"
chunk_header_size = 6 # 4fb8\r\n
# Current implementation reads one chunk of CHUNK_SIZE, then more chunks of size 4096.
# We want a chunk to split exactly after "#{request_body}\r", before the "\n".
edge_case_size = Puma::Const::CHUNK_SIZE + 4096 - header.size - chunk_header_size - 1
margin = 0 # 0 for only testing this specific case, increase to test more surrounding sizes
(-margin..margin).each do |i|
size = edge_case_size + i
request_body = '.' * size
request = "#{header}#{size.to_s(16)}\r\n#{request_body}\r\n0\r\n\r\n"
response = send_http_read_response request
assert_equal "HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", response
assert_equal size, Integer(content_length)
assert_equal request_body, body
end
end
def test_chunked_request_invalid_extension_header_length
body = nil
server_run(environment: :production) { |env|
body = env['rack.input'].read
[200, {}, [body]]
}
max_chunk_header_size = Puma::Client::MAX_CHUNK_HEADER_SIZE
# send valid request except for extension_header larger than limit
header = "GET / HTTP/1.1\r\nConnection: close\r\nContent-Length: 200\r\nTransfer-Encoding: chunked\r\n\r\n"
response = send_http_read_response "#{header}1;t=#{'x' * (max_chunk_header_size + 2)}\r\n1\r\nh\r\n4\r\nello\r\n0\r\n\r\n"
assert_equal "HTTP/1.1 400 Bad Request\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", response
end
def test_chunked_request_invalid_extension_header_length_split
body = nil
completed_loops = 0
server_run { |env|
body = env['rack.input'].read
[200, {}, [""]]
}
# includes 1st chunk length
socket = send_http "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\nTransfer-Encoding: chunked\r\n\r\n1;"
junk = "*" * 1_024
# Ubuntu allows us to close the client socket after an error write, and still
# read with the client. macOS and Windows won't allow a read.
begin
10.times do |i|
socket << junk
completed_loops = i
sleep 0.1
end
socket << "\r\nh\r\n4\r\nello\r\n0\r\n\r\n"
response = socket.read_response
refute_equal 'hello', body
assert_equal "HTTP/1.1 400 Bad Request\r\nConnection: close\r\ncontent-length: 0\r\n\r\n", response
# errors raised vary by OS
rescue Errno::EPIPE, Errno::ECONNABORTED, Errno::ECONNRESET
end
assert_equal 4, completed_loops
end
def test_chunked_request_pause_before_value
body = nil
content_length = nil
server_run { |env|
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
socket = send_http "GET / HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n1\r\n"
sleep 1
socket << "h\r\n4\r\nello\r\n0\r\n\r\n"
response = socket.read_response
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | true |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_normalize.rb | test/test_normalize.rb | # frozen_string_literal: true
require_relative "helper"
require "puma/request"
class TestNormalize < PumaTest
parallelize_me!
include Puma::Request
def test_comma_headers
env = {
"HTTP_X_FORWARDED_FOR" => "1.1.1.1",
"HTTP_X_FORWARDED,FOR" => "2.2.2.2",
}
req_env_post_parse env
expected = {
"HTTP_X_FORWARDED_FOR" => "1.1.1.1",
}
assert_equal expected, env
# Test that the iteration order doesn't matter
env = {
"HTTP_X_FORWARDED,FOR" => "2.2.2.2",
"HTTP_X_FORWARDED_FOR" => "1.1.1.1",
}
req_env_post_parse env
expected = {
"HTTP_X_FORWARDED_FOR" => "1.1.1.1",
}
assert_equal expected, env
end
def test_unmaskable_headers
env = {
"HTTP_CONTENT,LENGTH" => "100000",
"HTTP_TRANSFER,ENCODING" => "chunky"
}
req_env_post_parse env
expected = {
"HTTP_CONTENT,LENGTH" => "100000",
"HTTP_TRANSFER,ENCODING" => "chunky"
}
assert_equal expected, env
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_out_of_band_server.rb | test/test_out_of_band_server.rb | # frozen_string_literal: true
require_relative "helper"
class TestOutOfBandServer < PumaTest
parallelize_me!
def setup
@ios = []
@server = nil
@oob_finished = ConditionVariable.new
@app_finished = ConditionVariable.new
end
def teardown
@oob_finished.broadcast
@app_finished.broadcast
@server&.stop true
@ios.each do |io|
begin
io.close if io.is_a?(IO) && !io.closed?
rescue
ensure
io = nil
end
end
end
def new_connection
TCPSocket.new('127.0.0.1', @port).tap {|s| @ios << s}
rescue IOError
retry
end
def send_http(req)
new_connection << req
end
def send_http_and_read(req)
send_http(req).read
end
def oob_server(**options)
@request_count = 0
@oob_count = 0
in_oob = Mutex.new
@mutex = Mutex.new
oob_wait = options.delete(:oob_wait)
oob = {
block: -> do
in_oob.synchronize do
@mutex.synchronize do
@oob_count += 1
@oob_finished.signal
@oob_finished.wait(@mutex, 1) if oob_wait
end
end
end
}
app_wait = options.delete(:app_wait)
app = ->(_) do
raise 'OOB conflict' if in_oob.locked?
@mutex.synchronize do
@request_count += 1
@app_finished.signal
@app_finished.wait(@mutex, 1) if app_wait
end
[200, {}, [""]]
end
options[:min_threads] ||= 1
options[:max_threads] ||= 1
options[:log_writer] ||= Puma::LogWriter.strings
@server = Puma::Server.new app, nil, out_of_band: [oob], **options
@port = (@server.add_tcp_listener '127.0.0.1', 0).addr[1]
@server.run
sleep 0.15 if Puma.jruby?
end
# Sequential requests should trigger out_of_band after every request.
def test_sequential
n = 100
oob_server
n.times do
@mutex.synchronize do
send_http "GET / HTTP/1.0\r\n\r\n"
@oob_finished.wait(@mutex, 1)
end
end
assert_equal n, @request_count
assert_equal n, @oob_count
end
# Stream of requests on concurrent connections should trigger
# out_of_band hooks only once after the final request.
def test_stream
oob_server app_wait: true, max_threads: 2
n = 100
Array.new(n) {send_http("GET / HTTP/1.0\r\n\r\n")}
Thread.pass until @request_count == n
@mutex.synchronize do
@app_finished.signal
@oob_finished.wait(@mutex, 1)
end
assert_equal n, @request_count
assert_equal 1, @oob_count
end
# New requests should not get processed while OOB is running.
def test_request_overlapping_hook
oob_server oob_wait: true, max_threads: 2
# Establish connection for Req2 before OOB
req2 = new_connection
sleep 0.01
@mutex.synchronize do
send_http "GET / HTTP/1.0\r\n\r\n"
@oob_finished.wait(@mutex) # enter OOB
# Send Req2
req2 << "GET / HTTP/1.0\r\n\r\n"
# If Req2 is processed now it raises 'OOB Conflict' in the response.
sleep 0.01
@oob_finished.signal # exit OOB
# Req2 should be processed now.
@oob_finished.wait(@mutex, 1) # enter OOB
@oob_finished.signal # exit OOB
end
refute_match(/OOB conflict/, req2.read)
end
# Partial requests should not trigger OOB.
def test_partial_request
oob_server
new_connection.close
sleep 0.01
assert_equal 0, @oob_count
end
# OOB should be triggered following a completed request
# concurrent with other partial requests.
def test_partial_concurrent
oob_server max_threads: 2
@mutex.synchronize do
send_http("GET / HTTP/1.0\r\n\r\n")
100.times {new_connection.close}
@oob_finished.wait(@mutex, 1)
end
assert_equal 1, @oob_count
end
# OOB should block new connections from being accepted.
def test_blocks_new_connection
oob_server oob_wait: true, max_threads: 2
@mutex.synchronize do
send_http("GET / HTTP/1.0\r\n\r\n")
@oob_finished.wait(@mutex)
end
accepted = false
io = @server.binder.ios.last
io.stub(:accept_nonblock, -> {accepted = true; new_connection}) do
new_connection.close
sleep 0.01
end
refute accepted, 'New connection accepted during out of band'
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_web_concurrency_auto.rb | test/test_web_concurrency_auto.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/integration"
require_relative "helpers/test_puma/puma_socket"
require "puma/configuration"
require 'puma/log_writer'
class TestWebConcurrencyAuto < TestIntegration
include TestPuma::PumaSocket
ENV_WC_TEST = {
# -W0 removes logging of bundled gem warnings
"RUBYOPT" => "#{ENV["RUBYOPT"]} -W0",
"WEB_CONCURRENCY" => "auto"
}
def teardown
return if skipped?
super
end
# we use `cli_server` so no concurrent_ruby files are loaded in the test process
def test_web_concurrency_with_concurrent_ruby_available
skip_unless :fork
app = <<~APP
cpus = Concurrent.available_processor_count.to_i
silence_single_worker_warning if cpus == 1
app { |_| [200, {}, [cpus.to_s]] }
APP
cli_server set_pumactl_args, env: ENV_WC_TEST, config: app
# this is the value of `@options[:workers]` in Puma::Cluster
actual = @server_log[/\* +Workers: +(\d+)$/, 1]
workers = actual.to_i == 1 ? 1 : 2
get_worker_pids 0, workers # make sure at least one or more workers booted
expected = send_http_read_resp_body GET_11
assert_equal expected, actual
end
def test_web_concurrency_with_concurrent_ruby_unavailable
skip_unless :fork
_, err = capture_io do
assert_raises(LoadError) do
conf = Puma::Configuration.new({}, {}, ENV_WC_TEST)
# Mock the require to force it to fail
def conf.require(*args)
raise LoadError.new("Mocking system where concurrent-ruby is not available")
end
conf.puma_default_options(ENV_WC_TEST)
end
end
assert_includes err, 'Please add "concurrent-ruby" to your Gemfile'
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_integration_cluster.rb | test/test_integration_cluster.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/integration"
require "puma/configuration"
require "time"
class TestIntegrationCluster < TestIntegration
parallelize_me! if ::Puma.mri?
def workers ; 2 ; end
def setup
skip_unless :fork
super
end
def teardown
return if skipped?
super
end
def test_hot_restart_does_not_drop_connections_threads
restart_does_not_drop_connections num_threads: 10, total_requests: 3_000,
signal: :USR2
end
def test_hot_restart_does_not_drop_connections
restart_does_not_drop_connections num_threads: 1, total_requests: 1_000,
signal: :USR2
end
def test_phased_restart_does_not_drop_connections_threads
restart_does_not_drop_connections num_threads: 10, total_requests: 3_000,
signal: :USR1, config: "preload_app! false"
end
def test_phased_restart_does_not_drop_connections
restart_does_not_drop_connections num_threads: 1, total_requests: 1_000,
signal: :USR1, config: "preload_app! false"
end
def test_phased_restart_does_not_drop_connections_threads_fork_worker
restart_does_not_drop_connections num_threads: 10, total_requests: 3_000,
signal: :USR1, config: "fork_worker; preload_app! false"
end
def test_phased_restart_does_not_drop_connections_unix
restart_does_not_drop_connections num_threads: 1, total_requests: 1_000,
signal: :USR1, unix: true, config: "preload_app! false"
end
def test_pre_existing_unix
skip_unless :unix
File.open(@bind_path, mode: 'wb') { |f| f.puts 'pre existing' }
cli_server "-w #{workers} -q test/rackup/sleep_step.ru", unix: :unix
stop_server
assert File.exist?(@bind_path)
ensure
if UNIX_SKT_EXIST
File.unlink @bind_path if File.exist? @bind_path
end
end
def test_pre_existing_unix_stop_after_restart
skip_unless :unix
File.open(@bind_path, mode: 'wb') { |f| f.puts 'pre existing' }
cli_server "-w #{workers} -q test/rackup/sleep_step.ru", unix: :unix, config: "preload_app! false"
connection = connect(nil, unix: true)
restart_server connection
connect(nil, unix: true)
stop_server
assert File.exist?(@bind_path)
ensure
if UNIX_SKT_EXIST
File.unlink @bind_path if File.exist? @bind_path
end
end
def test_siginfo_thread_print
skip_unless_signal_exist? :INFO
cli_server "-w #{workers} -q test/rackup/hello.ru"
worker_pids = get_worker_pids
output = []
t = Thread.new { output << @server.readlines }
Process.kill :INFO, worker_pids.first
Process.kill :INT , @pid
t.join
assert_match "Thread: TID", output.join
end
def test_usr2_restart
_, new_reply = restart_server_and_listen("-q -w #{workers} test/rackup/hello.ru")
assert_equal "Hello World", new_reply
end
# Next two tests, one tcp, one unix
# Send requests 10 per second. Send 10, then :TERM server, then send another 30.
# No more than 10 should throw Errno::ECONNRESET.
def test_term_closes_listeners_tcp
term_closes_listeners unix: false
end
def test_term_closes_listeners_unix
term_closes_listeners unix: true
end
def test_term_exit_code
cli_server "-w #{workers} test/rackup/hello.ru"
_, status = stop_server
assert_equal 15, status
end
def test_term_suppress
cli_server "-w #{workers} -C test/config/suppress_exception.rb test/rackup/hello.ru"
_, status = stop_server
assert_equal 0, status
end
def test_after_booted_and_after_stopped
skip_unless_signal_exist? :TERM
cli_server "-w #{workers} " \
"-C test/config/event_after_booted_and_after_stopped.rb " \
"-C test/config/event_after_booted_exit.rb " \
"test/rackup/hello.ru",
no_wait: true
# below is logged after workers boot
assert wait_for_server_to_include('after_booted called')
assert wait_for_server_to_include('Goodbye!')
# below logged after workers are stopped
assert wait_for_server_to_include('after_stopped called')
wait_server 15
end
def test_term_worker_clean_exit
cli_server "-w #{workers} test/rackup/hello.ru"
# Get the PIDs of the child workers.
worker_pids = get_worker_pids
# Signal the workers to terminate, and wait for them to die.
Process.kill :TERM, @pid
wait_server 15
zombies = bad_exit_pids worker_pids
assert_empty zombies, "Process ids #{zombies} became zombies"
end
# mimicking stuck workers, test respawn with external TERM
def test_stuck_external_term_spawn
worker_respawn(0) do |phase0_worker_pids|
last = phase0_worker_pids.last
# test is tricky if only one worker is TERM'd, so kill all but
# spread out, so all aren't killed at once
phase0_worker_pids.each do |pid|
Process.kill :TERM, pid
sleep 4 unless pid == last
end
end
end
# From Ruby 2.6 to 3.2, `Process.detach` can delay or prevent
# `Process.wait2(-1)` from detecting a terminated child:
# https://bugs.ruby-lang.org/issues/19837. However,
# `Process.wait2(<child pid>)` still works properly. This bug has
# been fixed in Ruby 3.3.
def test_workers_respawn_with_process_detach
config = 'test/config/process_detach_before_fork.rb'
worker_respawn(0, workers, config) do |phase0_worker_pids|
phase0_worker_pids.each do |pid|
Process.kill :KILL, pid
end
end
# `test/config/process_detach_before_fork.rb` forks and detaches a
# process. Since MiniTest attempts to join all threads before
# finishing, terminate the process so that the test can end quickly
# if it passes.
pid_filename = File.join(Dir.tmpdir, 'process_detach_test.pid')
if File.exist?(pid_filename)
pid = File.read(pid_filename).chomp.to_i
File.unlink(pid_filename)
Process.kill :TERM, pid if pid > 0
end
end
# mimicking stuck workers, test restart
def test_stuck_phased_restart
worker_respawn { |phase0_worker_pids| Process.kill :USR1, @pid }
end
def test_puma_stats_clustered
worker_check_interval = 2
cli_server "-w 1 -t 1:1 #{set_pumactl_args unix: true} test/rackup/hello.ru",
config: "worker_check_interval #{worker_check_interval}"
sleep worker_check_interval + 1
stats = get_stats
assert_instance_of Hash, stats
last_status = stats['worker_status'].first['last_status']
Puma::Server::STAT_METHODS.each do |stat|
assert_includes last_status, stat.to_s
end
end
def test_worker_check_interval
# iso8601 2022-12-14T00:05:49Z
re_8601 = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z\z/
@control_tcp_port = UniquePort.call
worker_check_interval = 1
cli_server "-w 1 -t 1:1 --control-url tcp://#{HOST}:#{@control_tcp_port} --control-token #{TOKEN} test/rackup/hello.ru", config: "worker_check_interval #{worker_check_interval}"
sleep worker_check_interval + 1
checkin_1 = get_stats["worker_status"].first["last_checkin"]
assert_match re_8601, checkin_1
sleep worker_check_interval + 1
checkin_2 = get_stats["worker_status"].first["last_checkin"]
assert_match re_8601, checkin_2
# iso8601 sorts as a string
assert_operator(checkin_2, :>, checkin_1)
end
def test_worker_boot_timeout
timeout = 1
worker_timeout(timeout, 2, "failed to boot within \\\d+ seconds", "worker_boot_timeout #{timeout}; before_worker_boot { sleep #{timeout + 1} }")
end
def test_worker_timeout
skip 'Thread#name not available' unless Thread.current.respond_to?(:name)
timeout = Puma::Configuration::DEFAULTS[:worker_check_interval] + 1
config = <<~CONFIG
worker_timeout #{timeout}
before_worker_boot do
Thread.new do
sleep 1
Thread.list.find {|t| t.name == 'puma stat pld'}.kill
end
end
CONFIG
worker_timeout(timeout, 1, "failed to check in within \\\d+ seconds", config)
end
def test_idle_timeout
cli_server "-w #{workers} test/rackup/hello.ru", config: "idle_timeout 1"
get_worker_pids # wait for workers to boot
10.times {
fast_connect
sleep 0.5
}
sleep 1.15
assert_raises Errno::ECONNREFUSED, "Connection refused" do
connect
end
end
def test_queue_results_disabled
cli_server "-w #{workers} test/rackup/hello.ru", config: "queue_requests false"
get_worker_pids # wait for workers to boot
fast_connect
end
def test_worker_index_is_with_in_options_limit
cli_server "-C test/config/t3_conf.rb test/rackup/hello.ru"
get_worker_pids(0, 3) # this will wait till all the processes are up
worker_pid_was_present = File.file? "t3-worker-2-pid"
stop_server(Integer(File.read("t3-worker-2-pid")))
worker_index_within_number_of_workers = !File.file?("t3-worker-3-pid")
stop_server(Integer(File.read("t3-pid")))
assert(worker_pid_was_present)
assert(worker_index_within_number_of_workers)
ensure
File.unlink "t3-pid" if File.file? "t3-pid"
File.unlink "t3-worker-0-pid" if File.file? "t3-worker-0-pid"
File.unlink "t3-worker-1-pid" if File.file? "t3-worker-1-pid"
File.unlink "t3-worker-2-pid" if File.file? "t3-worker-2-pid"
File.unlink "t3-worker-3-pid" if File.file? "t3-worker-3-pid"
end
# use three workers to keep accepting clients
def test_fork_worker_before_refork
refork = Tempfile.new 'refork'
wrkrs = 3
cli_server "-w #{wrkrs} test/rackup/hello_with_delay.ru", config: <<~CONFIG
fork_worker 20
before_refork { File.write '#{refork.path}', 'Reforked' }
CONFIG
pids = get_worker_pids 0, wrkrs
socks = []
until refork.read == 'Reforked'
socks << fast_connect
sleep 0.004
end
100.times {
socks << fast_connect
sleep 0.004
}
socks.each { |s| read_body s }
refute_includes pids, get_worker_pids(1, wrkrs - 1)
end
# use three workers to keep accepting clients
def test_fork_worker_after_refork
refork = Tempfile.new 'refork2'
wrkrs = 3
cli_server "-w #{wrkrs} test/rackup/hello_with_delay.ru", config: <<~RUBY
fork_worker 20
before_refork { File.write '#{refork.path}', 'Before refork', mode: 'a+' }
after_refork { File.write '#{refork.path}', '-After refork', mode: 'a+' }
RUBY
pids = get_worker_pids 0, wrkrs
socks = []
until refork.read == 'Before refork-After refork'
refork.rewind
socks << fast_connect
sleep 0.004
end
100.times {
socks << fast_connect
sleep 0.004
}
socks.each { |s| read_body s }
refute_includes pids, get_worker_pids(1, wrkrs - 1)
end
def test_fork_worker_spawn
cli_server '', config: <<~CONFIG
workers 1
fork_worker 0
app do |_|
pid = spawn('ls', [:out, :err]=>'/dev/null')
sleep 0.01
exitstatus = Process.detach(pid).value.exitstatus
[200, {}, [exitstatus.to_s]]
end
CONFIG
assert_equal '0', read_body(connect)
end
def test_phased_restart_with_fork_worker_and_high_worker_count
worker_count = 10
cli_server "test/rackup/hello.ru", config: <<~CONFIG
fork_worker
worker_check_interval 1
# lower worker timeout from default (60) to avoid test timeout
worker_timeout 2
# to simulate worker 0 timeout, total boot time for all workers
# needs to exceed single worker timeout
workers #{worker_count}
preload_app! false
CONFIG
get_worker_pids 0, worker_count
Process.kill :USR1, @pid
get_worker_pids 1, worker_count
# below is so all of @server_log isn't simply output on failure
refute @server_log[/.*Terminating timed out worker.*/]
end
def test_refork_phased_restart_with_fork_worker_and_high_worker_count
worker_count = 10
cli_server "test/rackup/hello.ru", config: <<~CONFIG
fork_worker
worker_check_interval 1
# lower worker timeout from default (60) to avoid test timeout
worker_timeout 2
# to simulate worker 0 timeout, total boot time for all workers
# needs to exceed single worker timeout
workers #{worker_count}
CONFIG
get_worker_pids 0, worker_count
Process.kill :SIGURG, @pid
get_worker_pids 1, worker_count - 1
# below is so all of @server_log isn't simply output on failure
refute @server_log[/.*Terminating timed out worker.*/]
end
def test_prune_bundler_with_multiple_workers
cli_server "-C test/config/prune_bundler_with_multiple_workers.rb"
reply = read_body(connect)
assert_equal reply, "embedded app"
end
def test_load_path_includes_extra_deps
cli_server "-w #{workers} -C test/config/prune_bundler_with_deps.rb test/rackup/hello.ru"
assert wait_for_server_to_match(/^LOAD_PATH: .+?\/gems\/minitest-[\d.]+\/lib$/)
end
def test_load_path_does_not_include_nio4r
cli_server "-w #{workers} -C test/config/prune_bundler_with_deps.rb test/rackup/hello.ru"
get_worker_pids # reads thru 'LOAD_PATH:' data
# make sure we're seeing LOAD_PATH: logging
assert_match(/^LOAD_PATH: .+\/gems\/minitest-[\d.]+\/lib$/, @server_log)
refute_match(%r{gems/nio4r-[\d.]+/lib$}, @server_log)
end
def test_json_gem_not_required_in_master_process
cli_server "-w #{workers} -C test/config/prune_bundler_print_json_defined.rb test/rackup/hello.ru"
assert wait_for_server_to_include('defined?(::JSON): nil')
end
def test_nio4r_gem_not_required_in_master_process
cli_server "-w #{workers} -C test/config/prune_bundler_print_nio_defined.rb test/rackup/hello.ru"
assert wait_for_server_to_include('defined?(::NIO): nil')
end
def test_nio4r_gem_not_required_in_master_process_when_using_control_server
@control_tcp_port = UniquePort.call
control_opts = "--control-url tcp://#{HOST}:#{@control_tcp_port} --control-token #{TOKEN}"
cli_server "-w #{workers} #{control_opts} -C test/config/prune_bundler_print_nio_defined.rb test/rackup/hello.ru"
assert wait_for_server_to_include('Starting control server')
assert wait_for_server_to_include('defined?(::NIO): nil')
end
def test_application_is_loaded_exactly_once_if_using_preload_app
cli_server "-w #{workers} --preload test/rackup/write_to_stdout_on_boot.ru"
get_worker_pids
loading_app_count = @server_log.scan("Loading app").length
assert_equal 1, loading_app_count
end
def test_application_is_loaded_exactly_once_if_using_fork_worker
cli_server "-w #{workers} --fork-worker test/rackup/write_to_stdout_on_boot.ru"
get_worker_pids
loading_app_count = @server_log.scan("Loading app").length
assert_equal 1, loading_app_count # loaded in worker 0
@server_log.clear
Process.kill :SIGURG, @pid
get_worker_pids 1, workers - 1
loading_app_count = @server_log.scan("Loading app").length
assert_equal 0, loading_app_count
end
def test_application_is_loaded_exactly_once_if_using_preload_app_with_fork_worker
cli_server "-w #{workers} --preload --fork-worker test/rackup/write_to_stdout_on_boot.ru"
get_worker_pids
loading_app_count = @server_log.scan("Loading app").length
assert_equal 1, loading_app_count # loaded in master
@server_log.clear
Process.kill :SIGURG, @pid
get_worker_pids 1, workers - 1
loading_app_count = @server_log.scan("Loading app").length
assert_equal 0, loading_app_count
end
def test_warning_message_outputted_when_single_worker
cli_server "-w 1 test/rackup/hello.ru"
assert wait_for_server_to_include('Worker 0 (PID')
assert_match(/WARNING: Detected running cluster mode with 1 worker/, @server_log)
end
def test_warning_message_outputted_when_ruby_mn_threads_is_set
cli_server "-w 1 test/rackup/hello.ru", env: { 'RUBY_MN_THREADS' => '1' }
assert wait_for_server_to_include('Worker 0 (PID')
assert_match(/WARNING: Detected `RUBY_MN_THREADS/, @server_log)
end
def test_warning_message_not_outputted_when_single_worker_silenced
cli_server "-w 1 test/rackup/hello.ru", config: "silence_single_worker_warning"
assert wait_for_server_to_include('Worker 0 (PID')
refute_match(/WARNING: Detected running cluster mode with 1 worker/, @server_log)
end
def test_signal_ttin
cli_server "-w 2 test/rackup/hello.ru"
get_worker_pids # to consume server logs
Process.kill :TTIN, @pid
assert wait_for_server_to_match(/Worker 2 \(PID: \d+\) booted in/)
end
def test_signal_ttou
cli_server "-w 2 test/rackup/hello.ru"
get_worker_pids # to consume server logs
Process.kill :TTOU, @pid
assert wait_for_server_to_match(/Worker 1 \(PID: \d+\) terminating/)
end
def test_culling_strategy_youngest
cli_server "-w 2 test/rackup/hello.ru", config: "worker_culling_strategy :youngest"
get_worker_pids # to consume server logs
Process.kill :TTIN, @pid
assert wait_for_server_to_match(/Worker 2 \(PID: \d+\) booted in/)
Process.kill :TTOU, @pid
assert wait_for_server_to_match(/Worker 2 \(PID: \d+\) terminating/)
end
def test_culling_strategy_oldest
cli_server "-w 2 test/rackup/hello.ru", config: "worker_culling_strategy :oldest"
get_worker_pids # to consume server logs
Process.kill :TTIN, @pid
assert wait_for_server_to_match(/Worker 2 \(PID: \d+\) booted in/)
Process.kill :TTOU, @pid
assert wait_for_server_to_match(/Worker 0 \(PID: \d+\) terminating/)
end
def test_culling_strategy_oldest_fork_worker
cli_server "-w 2 test/rackup/hello.ru", config: <<~CONFIG
worker_culling_strategy :oldest
fork_worker
CONFIG
get_worker_pids # to consume server logs
Process.kill :TTIN, @pid
assert wait_for_server_to_match(/Worker 2 \(PID: \d+\) booted in/)
Process.kill :TTOU, @pid
assert wait_for_server_to_match(/Worker 1 \(PID: \d+\) terminating/)
end
def test_hook_data
cli_server "-C test/config/hook_data.rb test/rackup/hello.ru"
get_worker_pids 0, 2 # make sure workers are booted
stop_server
ary = Array.new(2) do |_index|
wait_for_server_to_match(/(index \d data \d)/, 1)
end.sort
assert_equal 'index 0 data 0', ary[0]
assert_equal 'index 1 data 1', ary[1]
end
def test_after_worker_shutdown_hook
cli_server "-C test/config/after_shutdown_hook.rb test/rackup/hello.ru"
get_worker_pids 0, 2 # make sure workers are booted
stop_server
ary = Array.new(2) do |_index|
wait_for_server_to_match(/(after_worker_shutdown worker=\d status=\d+)/, 1)
end.sort
assert_equal 'after_worker_shutdown worker=0 status=0', ary[0]
assert_equal 'after_worker_shutdown worker=1 status=0', ary[1]
end
def test_worker_hook_warning_cli
cli_server "-w2 test/rackup/hello.ru", config: <<~CONFIG
before_worker_boot(:test) do |index, data|
data[:test] = index
end
CONFIG
get_worker_pids
line = @server_log[/^Warning.+before_worker_boot.+/]
refute line, "Warning below should not be shown!\n#{line}"
end
def test_worker_hook_warning_web_concurrency
cli_server "test/rackup/hello.ru",
env: { 'WEB_CONCURRENCY' => '2'},
config: <<~CONFIG
before_worker_boot(:test) do |index, data|
data[:test] = index
end
CONFIG
get_worker_pids
line = @server_log[/^Warning.+.+before_worker_boot.+/]
refute line, "Warning below should not be shown!\n#{line}"
end
def test_puma_debug_worker_hook
cli_server "-w #{workers} test/rackup/hello.ru", puma_debug: true, config: "before_worker_boot {}"
assert wait_for_server_to_include("Running before_worker_boot hooks")
end
def test_puma_debug_loaded_exts
cli_server "-w #{workers} test/rackup/hello.ru", puma_debug: true
assert wait_for_server_to_include('Loaded Extensions - worker 0:')
assert wait_for_server_to_include('Loaded Extensions - master:')
@pid = @server.pid
end
private
def worker_timeout(timeout, iterations, details, config, log: nil)
cli_server "-w #{workers} -t 1:1 test/rackup/hello.ru", config: config
pids = []
re = /Terminating timed out worker \(Worker \d+ #{details}\): (\d+)/
Timeout.timeout(iterations * (timeout + 1.5)) do
while (pids.size < workers * iterations)
idx = wait_for_server_to_match(re, 1).to_i
pids << idx
end
end
assert_equal pids, pids.uniq
end
# Send requests 10 per second. Send 10, then :TERM server, then send another 30.
# No more than 10 should throw Errno::ECONNRESET.
def term_closes_listeners(unix: false)
cli_server "-w #{workers} -t 0:6 -q test/rackup/sleep_step.ru", unix: unix
threads = []
replies = []
mutex = Mutex.new
div = 10
refused = thread_run_refused unix: unix
41.times.each do |i|
if i == 10
threads << Thread.new do
sleep i.to_f/div
Process.kill :TERM, @pid
mutex.synchronize { replies[i] = :term_sent }
end
else
threads << Thread.new do
thread_run_step replies, i.to_f/div, 1, i, mutex, refused, unix: unix
end
end
end
threads.each(&:join)
failures = replies.count(:failure)
successes = replies.count(:success)
resets = replies.count(:reset)
refused = replies.count(:refused)
read_timeouts = replies.count(:read_timeout)
r_success = replies.rindex(:success)
l_reset = replies.index(:reset)
r_reset = replies.rindex(:reset)
l_refused = replies.index(:refused)
msg = "#{successes} successes, #{resets} resets, #{refused} refused, #{failures} failures, #{read_timeouts} read timeouts"
assert_equal 0, failures, msg
assert_equal 0, read_timeouts, msg
assert_operator 9, :<=, successes, msg
assert_operator 10, :>=, resets , msg
assert_operator 20, :<=, refused , msg
# Interleaved asserts
# UNIX binders do not generate :reset items
if l_reset
assert_operator r_success, :<, l_reset , "Interleaved success and reset"
assert_operator r_reset , :<, l_refused, "Interleaved reset and refused"
else
assert_operator r_success, :<, l_refused, "Interleaved success and refused"
end
ensure
if passed?
$debugging_info << "#{full_name}\n #{msg}\n"
else
$debugging_info << "#{full_name}\n #{msg}\n#{replies.inspect}\n"
end
end
def worker_respawn(phase = 1, size = workers, config = 'test/config/worker_respawn.rb')
threads = []
cli_server "-w #{workers} -t 1:1 -C #{config} test/rackup/sleep_pid.ru"
# make sure two workers have booted
phase0_worker_pids = get_worker_pids
[35, 40].each do |sleep_time|
threads << Thread.new do
begin
connect "sleep#{sleep_time}"
# stuck connections will raise IOError or Errno::ECONNRESET
# when shutdown
rescue IOError, Errno::ECONNRESET
end
end
end
@start_time = Time.now.to_f
# below should 'cancel' the phase 0 workers, either via phased_restart or
# externally TERM'ing them
yield phase0_worker_pids
# wait for new workers to boot
phase1_worker_pids = get_worker_pids phase
# should be empty if all phase 0 workers cleanly exited
phase0_exited = bad_exit_pids phase0_worker_pids
# Since 35 is the shorter of the two requests, server should restart
# and cancel both requests
assert_operator (Time.now.to_f - @start_time).round(2), :<, 35
msg = "phase0_worker_pids #{phase0_worker_pids.inspect} phase1_worker_pids #{phase1_worker_pids.inspect} phase0_exited #{phase0_exited.inspect}"
assert_equal workers, phase0_worker_pids.length, msg
assert_equal workers, phase1_worker_pids.length, msg
assert_empty phase0_worker_pids & phase1_worker_pids, "#{msg}\nBoth workers should be replaced with new"
assert_empty phase0_exited, msg
threads.each { |th| Thread.kill th }
end
# Returns an array of pids still in the process table, so it should
# be empty for a clean exit.
# Process.kill should raise the Errno::ESRCH exception, indicating the
# process is dead and has been reaped.
def bad_exit_pids(pids)
t = pids.map do |pid|
begin
pid if Process.kill 0, pid
rescue Errno::ESRCH
nil
end
end
t.compact!; t
end
# used in loop to create several 'requests'
def thread_run_pid(replies, delay, sleep_time, mutex, refused, unix: false)
begin
sleep delay
s = fast_connect "sleep#{sleep_time}", unix: unix
body = read_body(s, 20)
mutex.synchronize { replies << body }
rescue Errno::ECONNRESET
# connection was accepted but then closed
# client would see an empty response
mutex.synchronize { replies << :reset }
rescue *refused
mutex.synchronize { replies << :refused }
rescue Timeout::Error
mutex.synchronize { replies << :read_timeout }
end
end
# used in loop to create several 'requests'
def thread_run_step(replies, delay, sleep_time, step, mutex, refused, unix: false)
begin
sleep delay
s = connect "sleep#{sleep_time}-#{step}", unix: unix
body = read_body(s, 20)
if body[/\ASlept /]
mutex.synchronize { replies[step] = :success }
else
mutex.synchronize { replies[step] = :failure }
end
rescue Errno::ECONNRESET
# connection was accepted but then closed
# client would see an empty response
mutex.synchronize { replies[step] = :reset }
rescue *refused
mutex.synchronize { replies[step] = :refused }
rescue Timeout::Error
mutex.synchronize { replies[step] = :read_timeout }
end
end
end if ::Process.respond_to?(:fork)
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_rack_handler.rb | test/test_rack_handler.rb | # frozen_string_literal: true
require_relative "helper"
# Most tests check that ::Rack::Handler::Puma works by itself
# RackUp#test_bin runs Puma using the rackup bin file
module TestRackUp
require "rack/handler/puma"
require "puma/events"
begin
require 'rackup/version'
rescue LoadError
end
class TestOnBootedHandler < PumaTest
def app
Proc.new {|env| @input = env; [200, {}, ["hello world"]]}
end
# `Verbose: true` is included for `NameError`,
# see https://github.com/puma/puma/pull/3118
def test_after_booted
after_booted = false
events = Puma::Events.new
events.after_booted do
after_booted = true
end
launcher = nil
thread = Thread.new do
Rack::Handler::Puma.run(app, events: events, Verbose: true, Silent: true, Port: 0) do |l|
launcher = l
end
end
# Wait for launcher to boot
Timeout.timeout(10) do
sleep 0.5 until launcher
end
sleep 1.5 unless Puma::IS_MRI
launcher.stop
thread.join
assert_equal after_booted, true
end
end
class TestPathHandler < PumaTest
def app
Proc.new {|env| @input = env; [200, {}, ["hello world"]]}
end
def setup
@input = nil
end
def in_handler(app, options = {})
options[:Port] ||= 0
options[:Silent] = true
@launcher = nil
thread = Thread.new do
::Rack::Handler::Puma.run(app, **options) do |s, p|
@launcher = s
end
end
# Wait for launcher to boot
Timeout.timeout(10) do
sleep 0.5 until @launcher
end
sleep 1.5 unless Puma::IS_MRI
yield @launcher
ensure
@launcher&.stop
thread&.join
end
def test_handler_boots
host = '127.0.0.1'
port = UniquePort.call
opts = { Host: host, Port: port }
in_handler(app, opts) do |launcher|
hit(["http://#{host}:#{port}/test"])
assert_equal("/test", @input["PATH_INFO"])
end
end
end
class TestUserSuppliedOptionsPortIsSet < PumaTest
def setup
@options = {}
@options[:user_supplied_options] = [:Port]
end
def test_port_wins_over_config
user_port = 5001
file_port = 6001
Dir.mktmpdir do |d|
Dir.chdir(d) do
FileUtils.mkdir("config")
File.open("config/puma.rb", "w") { |f| f << "port #{file_port}" }
@options[:Port] = user_port
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["tcp://0.0.0.0:#{user_port}"], conf.options[:binds]
end
end
end
end
class TestUserSuppliedOptionsHostIsSet < PumaTest
def setup
@options = {}
@options[:user_supplied_options] = [:Host]
end
def test_host_uses_supplied_port_default
user_port = rand(1000..9999)
user_host = "123.456.789"
@options[:Host] = user_host
@options[:Port] = user_port
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["tcp://#{user_host}:#{user_port}"], conf.options[:binds]
end
def test_ipv6_host_supplied_port_default
@options[:Host] = "::1"
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["tcp://[::1]:9292"], conf.options[:binds]
end
def test_ssl_host_supplied_port_default
@options[:Host] = "ssl://127.0.0.1"
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["ssl://127.0.0.1:9292"], conf.options[:binds]
end
def test_relative_unix_host
@options[:Host] = "./relative.sock"
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["unix://./relative.sock"], conf.options[:binds]
end
def test_absolute_unix_host
@options[:Host] = "/absolute.sock"
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["unix:///absolute.sock"], conf.options[:binds]
end
def test_abstract_unix_host
@options[:Host] = "@abstract.sock"
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["unix://@abstract.sock"], conf.options[:binds]
end
end
class TestUserSuppliedOptionsIsEmpty < PumaTest
def setup
@options = {}
@options[:user_supplied_options] = []
end
def test_config_file_wins_over_port
user_port = 5001
file_port = 6001
Dir.mktmpdir do |d|
Dir.chdir(d) do
FileUtils.mkdir("config")
File.open("config/puma.rb", "w") { |f| f << "port #{file_port}" }
@options[:Port] = user_port
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["tcp://0.0.0.0:#{file_port}"], conf.options[:binds]
end
end
end
def test_default_host_when_using_config_file
user_port = 5001
file_port = 6001
Dir.mktmpdir do |d|
Dir.chdir(d) do
FileUtils.mkdir("config")
File.open("config/puma.rb", "w") { |f| f << "port #{file_port}" }
@options[:Host] = "localhost"
@options[:Port] = user_port
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["tcp://localhost:#{file_port}"], conf.options[:binds]
end
end
end
def test_default_host_when_using_config_file_with_explicit_host
user_port = 5001
file_port = 6001
Dir.mktmpdir do |d|
Dir.chdir(d) do
FileUtils.mkdir("config")
File.open("config/puma.rb", "w") { |f| f << "port #{file_port}, '1.2.3.4'" }
@options[:Host] = "localhost"
@options[:Port] = user_port
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["tcp://1.2.3.4:#{file_port}"], conf.options[:binds]
end
end
end
end
class TestUserSuppliedOptionsIsNotPresent < PumaTest
def setup
@options = {}
end
def test_default_port_when_no_config_file
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["tcp://0.0.0.0:9292"], conf.options[:binds]
end
def test_config_wins_over_default
file_port = 6001
Dir.mktmpdir do |d|
Dir.chdir(d) do
FileUtils.mkdir("config")
File.open("config/puma.rb", "w") { |f| f << "port #{file_port}" }
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["tcp://0.0.0.0:#{file_port}"], conf.options[:binds]
end
end
end
def test_user_port_wins_over_default_when_user_supplied_is_blank
user_port = 5001
@options[:user_supplied_options] = []
@options[:Port] = user_port
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["tcp://0.0.0.0:#{user_port}"], conf.options[:binds]
end
def test_user_port_wins_over_default
user_port = 5001
@options[:Port] = user_port
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["tcp://0.0.0.0:#{user_port}"], conf.options[:binds]
end
def test_user_port_wins_over_config
user_port = 5001
file_port = 6001
Dir.mktmpdir do |d|
Dir.chdir(d) do
FileUtils.mkdir("config")
File.open("config/puma.rb", "w") { |f| f << "port #{file_port}" }
@options[:Port] = user_port
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal ["tcp://0.0.0.0:#{user_port}"], conf.options[:binds]
end
end
end
def test_default_log_request_when_no_config_file
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal false, conf.options[:log_requests]
end
def test_file_log_requests_wins_over_default_config
file_log_requests_config = true
@options[:config_files] = [
'test/config/t1_conf.rb'
]
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal file_log_requests_config, conf.options[:log_requests]
end
def test_user_log_requests_wins_over_file_config
user_log_requests_config = false
@options[:log_requests] = user_log_requests_config
@options[:config_files] = [
'test/config/t1_conf.rb'
]
conf = ::Rack::Handler::Puma.config(->{}, @options)
conf.clamp
assert_equal user_log_requests_config, conf.options[:log_requests]
end
end
# Run using IO.popen so we don't load Rack and/or Rackup in the main process
class RackUp < PumaTest
def setup
FileUtils.copy_file 'test/rackup/hello.ru', 'config.ru'
end
def teardown
FileUtils.rm 'config.ru'
end
def test_bin
pid = nil
# JRuby & TruffleRuby take a long time using IO.popen
skip_unless :mri
io = IO.popen "rackup -p 0"
io.wait_readable 2
sleep 0.7
log = io.sysread 2_048
pid = log[/PID: (\d+)/, 1] || io.pid
assert_includes log, 'Puma version'
assert_includes log, 'Use Ctrl-C to stop'
ensure
if pid
if Puma::IS_WINDOWS
`taskkill /F /PID #{pid}`
else
`kill -s KILL #{pid}`
end
end
end
def test_rackup1
pid = nil
# JRuby & TruffleRuby take a long time using IO.popen
skip_unless :mri
env = {'RUBYOPT' => '-rbundler/setup -rrack/version -rrack/handler -rrackup -rrack/handler/puma'}
io = IO.popen env, "ruby -e 'puts Rackup::VERSION'"
io.wait_readable 2
pid = io.pid
log = io.sysread 2_048
assert_start_with log, '1.0'
ensure
if pid
if Puma::IS_WINDOWS
`taskkill /F /PID #{pid}`
else
`kill -s KILL #{pid}`
end
end
end if Object.const_defined?(:Rackup) && ::Rackup::VERSION.start_with?('1.')
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_null_io.rb | test/test_null_io.rb | # frozen_string_literal: true
require_relative "helper"
require "puma/null_io"
class TestNullIO < PumaTest
parallelize_me!
attr_accessor :nio
def setup
self.nio = Puma::NullIO.new
end
def test_eof_returns_true
assert nio.eof?
end
def test_gets_returns_nil
assert_nil nio.gets
end
def test_string_returns_empty_string
assert_equal "", nio.string
end
def test_each_never_yields
nio.instance_variable_set(:@foo, :baz)
nio.each { @foo = :bar }
assert_equal :baz, nio.instance_variable_get(:@foo)
end
def test_read_with_no_arguments
assert_equal "", nio.read
end
def test_read_with_nil_length
assert_equal "", nio.read(nil)
end
def test_read_with_zero_length
assert_equal "", nio.read(0)
end
def test_read_with_positive_integer_length
assert_nil nio.read(1)
end
def test_read_with_negative_length
error = assert_raises ArgumentError do
nio.read(-42)
end
# 2nd match is TruffleRuby
assert_match(/negative length -42 given|length must not be negative/, error.message)
end
def test_read_with_nil_buffer
assert_equal "", nio.read(nil, nil)
assert_equal "", nio.read(0, nil)
assert_nil nio.read(1, nil)
end
class ImplicitString
def to_str
"ImplicitString".b
end
end
def test_read_with_implicit_string_like_buffer
assert_equal "", nio.read(nil, ImplicitString.new)
end
def test_read_with_invalid_buffer
error = assert_raises TypeError do
nio.read(nil, Object.new)
end
assert_includes error.message, "no implicit conversion of Object into String"
error = assert_raises TypeError do
nio.read(0, Object.new)
end
error = assert_raises TypeError do
nio.read(1, Object.new)
end
assert_includes error.message, "no implicit conversion of Object into String"
end
def test_read_with_frozen_buffer
# Remove when Ruby 2.4 is no longer supported
err = defined? ::FrozenError ? ::FrozenError : ::RuntimeError
assert_raises err do
nio.read(nil, "".freeze)
end
assert_raises err do
nio.read(0, "".freeze)
end
assert_raises err do
nio.read(20, "".freeze)
end
end
def test_read_with_length_and_buffer
buf = "random_data".b
assert_nil nio.read(1, buf)
assert_equal "".b, buf
end
def test_read_with_buffer
buf = "random_data".b
assert_same buf, nio.read(nil, buf)
assert_equal "", buf
end
def test_size
assert_equal 0, nio.size
end
def test_pos
assert_equal 0, nio.pos
end
def test_seek_returns_0
assert_equal 0, nio.seek(0)
assert_equal 0, nio.seek(100)
end
def test_seek_negative_raises
error = assert_raises ArgumentError do
nio.read(-1)
end
# TruffleRuby - length must not be negative
assert_match(/negative length -1 given|length must not be negative/, error.message)
end
def test_sync_returns_true
assert_equal true, nio.sync
end
def test_flush_returns_self
assert_equal nio, nio.flush
end
def test_closed_returns_false
assert_equal false, nio.closed?
end
def test_set_encoding
assert_equal nio, nio.set_encoding(Encoding::BINARY)
end
def test_external_encoding
assert_equal Encoding::ASCII_8BIT, nio.external_encoding
end
def test_binmode
assert_equal nio, nio.binmode
end
def test_binmode?
assert nio.binmode?
end
end
# Run the same tests but against an empty file to
# ensure all the test behavior is accurate
class TestNullIOConformance < TestNullIO
def setup
# client.rb sets 'binmode` on all Tempfiles
self.nio = ::Tempfile.create.binmode
nio.sync = true
end
def teardown
return unless nio.is_a? ::File
nio.close
File.unlink nio.path
end
def test_string_returns_empty_string
self.nio = StringIO.new
super
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_cluster_accept_loop_delay.rb | test/test_cluster_accept_loop_delay.rb | # frozen_string_literal: true
require_relative "helper"
require "puma/cluster_accept_loop_delay"
class TestClusterAcceptLoopDelay < PumaTest
parallelize_me!
def test_off_when_fewer_than_two_workers
cal_delay = Puma::ClusterAcceptLoopDelay.new(
workers: 2,
max_delay: 1
)
assert_equal true, cal_delay.on?
cal_delay = Puma::ClusterAcceptLoopDelay.new(
workers: 1,
max_delay: 1
)
assert_equal false, cal_delay.on?
end
def test_zero_max_delay_always_returns_zero
cal_delay = Puma::ClusterAcceptLoopDelay.new(
workers: 2,
max_delay: 0
)
assert_equal false, cal_delay.on?
assert_equal 0, cal_delay.calculate(busy_threads_plus_todo: 0, max_threads: 16)
assert_equal 0, cal_delay.calculate(busy_threads_plus_todo: 42, max_threads: 16)
assert_equal 0, cal_delay.calculate(busy_threads_plus_todo: 42 * 42, max_threads: 16)
end
def test_zero_busy_threads_plus_todo_always_returns_zero
cal_delay = Puma::ClusterAcceptLoopDelay.new(
workers: 2,
max_delay: 0.005
)
assert_equal 0, cal_delay.calculate(busy_threads_plus_todo: 0, max_threads: 10)
end
def test_linear_increase_with_busy_threads_plus_todo
cal_delay = Puma::ClusterAcceptLoopDelay.new(
workers: 2,
max_delay: 0.05
)
assert_in_delta 0, cal_delay.calculate(busy_threads_plus_todo: 0, max_threads: 1), 0.001
assert_in_delta 0.002, cal_delay.calculate(busy_threads_plus_todo: 1, max_threads: 1), 0.001
assert_in_delta 0.05, cal_delay.calculate(busy_threads_plus_todo: 25, max_threads: 1), 0.001
assert_in_delta 0.05, cal_delay.calculate(busy_threads_plus_todo: 26, max_threads: 1), 0.001
end
def test_always_return_float_when_non_zero
# Dividing integers accidentally returns 0 so want to make sure we are correctly converting to float before division
cal_delay = Puma::ClusterAcceptLoopDelay.new(
workers: 2,
max_delay: Integer(5)
)
assert_in_delta 0, cal_delay.calculate(busy_threads_plus_todo: 0.to_f, max_threads: Integer(1)), 0.001
assert_equal Float, cal_delay.calculate(busy_threads_plus_todo: Integer(25), max_threads: Integer(1)).class
assert_in_delta 5, cal_delay.calculate(busy_threads_plus_todo: 25, max_threads: Integer(1)), 0.001
end
def test_extreme_busy_values_produce_sensible_delays
cal_delay = Puma::ClusterAcceptLoopDelay.new(
workers: 2,
max_delay: 0.05
)
assert_in_delta 0, cal_delay.calculate(busy_threads_plus_todo: -10, max_threads: 5), 0.001
assert_in_delta 0.05, cal_delay.calculate(busy_threads_plus_todo: Float::INFINITY, max_threads: 5), 0.001
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_puma_server_current.rb | test/test_puma_server_current.rb | # frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2023, by Samuel Williams.
require_relative "helper"
require "puma/server"
class PumaServerCurrentApplication
def call(env)
[200, {"Content-Type" => "text/plain"}, [Puma::Server.current.to_s]]
end
end
class PumaServerCurrentTest < PumaTest
parallelize_me!
def setup
@tester = PumaServerCurrentApplication.new
@server = Puma::Server.new @tester, nil, {log_writer: Puma::LogWriter.strings, clean_thread_locals: true}
@port = (@server.add_tcp_listener "127.0.0.1", 0).addr[1]
@tcp = "http://127.0.0.1:#{@port}"
@url = URI.parse(@tcp)
@server.run
end
def teardown
@server.stop(true)
end
def test_clean_thread_locals
server_string = @server.to_s
responses = []
# This must be a persistent connection to hit the `clean_thread_locals` code path.
Net::HTTP.new(@url.host, @url.port).start do |connection|
3.times do
responses << connection.get("/").body
end
end
assert_equal [server_string]*3, responses
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_integration_pumactl.rb | test/test_integration_pumactl.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/integration"
class TestIntegrationPumactl < TestIntegration
include TmpPath
parallelize_me! if ::Puma.mri?
def workers ; 2 ; end
def setup
super
@control_path = nil
@state_path = tmp_path('.state')
end
def teardown
super
refute @control_path && File.exist?(@control_path), "Control path must be removed after stop"
ensure
[@state_path, @control_path].each { |p| File.unlink(p) rescue nil }
end
def test_stop_tcp
skip_if :jruby, :truffleruby # Undiagnose thread race. TODO fix
@control_tcp_port = UniquePort.call
cli_server "-q test/rackup/sleep.ru #{set_pumactl_args} -S #{@state_path}"
cli_pumactl "stop"
wait_server
end
def test_stop_unix
ctl_unix
end
def test_halt_unix
ctl_unix 'halt'
end
def ctl_unix(signal='stop')
skip_unless :unix
stderr = Tempfile.new(%w(stderr .log))
cli_server "-q test/rackup/sleep.ru #{set_pumactl_args unix: true} -S #{@state_path}",
config: "stdout_redirect nil, '#{stderr.path}'",
unix: true
cli_pumactl signal, unix: true
wait_server
refute_match 'error', File.read(stderr.path)
end
def test_phased_restart_cluster
skip_unless :fork
cli_server "test/rackup/sleep.ru #{set_pumactl_args unix: true}", unix: true, config: <<~RUBY
quiet
workers #{workers}
preload_app! false
state_path "#{@state_path}"
RUBY
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
s = UNIXSocket.new @bind_path
@ios_to_close << s
s << "GET /sleep1 HTTP/1.0\r\n\r\n"
# Get the PIDs of the phase 0 workers.
phase0_worker_pids = get_worker_pids 0
assert File.exist? @bind_path
# Phased restart
cli_pumactl "phased-restart", unix: true
# Get the PIDs of the phase 1 workers.
phase1_worker_pids = get_worker_pids 1
msg = "phase 0 pids #{phase0_worker_pids.inspect} phase 1 pids #{phase1_worker_pids.inspect}"
assert_equal workers, phase0_worker_pids.length, msg
assert_equal workers, phase1_worker_pids.length, msg
assert_empty phase0_worker_pids & phase1_worker_pids, "#{msg}\nBoth workers should be replaced with new"
assert File.exist?(@bind_path), "Bind path must exist after phased restart"
cli_pumactl "stop", unix: true
wait_server
assert_operator Process.clock_gettime(Process::CLOCK_MONOTONIC) - start, :<, (DARWIN ? 8 : 7)
end
def test_refork_cluster
skip_unless :fork
wrkrs = 3
cli_server "-q -w #{wrkrs} test/rackup/sleep.ru #{set_pumactl_args unix: true} -S #{@state_path}",
config: 'fork_worker 50',
unix: true
start = Time.now
fast_connect("sleep1", unix: true)
# Get the PIDs of the phase 0 workers.
phase0_worker_pids = get_worker_pids 0, wrkrs
assert File.exist? @bind_path
cli_pumactl "refork", unix: true
# Get the PIDs of the phase 1 workers.
phase1_worker_pids = get_worker_pids 1, wrkrs - 1
msg = "phase 0 pids #{phase0_worker_pids.inspect} phase 1 pids #{phase1_worker_pids.inspect}"
assert_equal wrkrs , phase0_worker_pids.length, msg
assert_equal wrkrs - 1, phase1_worker_pids.length, msg
assert_empty phase0_worker_pids & phase1_worker_pids, "#{msg}\nBoth workers should be replaced with new"
assert File.exist?(@bind_path), "Bind path must exist after phased refork"
cli_pumactl "stop", unix: true
wait_server
assert_operator Time.now - start, :<, 60
end
def test_prune_bundler_with_multiple_workers
skip_unless :fork
cli_server "-q -C test/config/prune_bundler_with_multiple_workers.rb #{set_pumactl_args unix: true} -S #{@state_path}", unix: true
socket = fast_connect(unix: true)
headers, body = read_response(socket)
assert_includes headers, "200 OK"
assert_includes body, "embedded app"
cli_pumactl "stop", unix: true
wait_server
end
def test_kill_unknown
skip_if :jruby
# we run ls to get a 'safe' pid to pass off as puma in cli stop
# do not want to accidentally kill a valid other process
io = IO.popen(windows? ? "dir" : "ls")
safe_pid = io.pid
Process.wait safe_pid
sout = StringIO.new
e = assert_raises SystemExit do
Puma::ControlCLI.new(%W!-p #{safe_pid} stop!, sout).run
end
sout.rewind
# windows bad URI(is not URI?)
assert_match(/No pid '\d+' found|bad URI ?\(is not URI\?\)/, sout.readlines.join(""))
assert_equal(1, e.status)
end
def test_config_deprecated
conf_path = "test/config/config_with_deprecated.rb"
out = cli_pumactl_spawn "-F #{conf_path} halt", no_bind: true
refute_start_with out.read, 'undefined method'
end
# calls pumactl with both a config file and a state file, making sure that
# puma files are required, see https://github.com/puma/puma/issues/3186
def test_require_dependencies
skip_if :jruby
conf_path = tmp_path '.config.rb'
@tcp_port = UniquePort.call
@control_tcp_port = UniquePort.call
File.write conf_path , <<~CONF
state_path "#{@state_path}"
bind "tcp://127.0.0.1:#{@tcp_port}"
workers 0
before_fork do
end
activate_control_app "tcp://127.0.0.1:#{@control_tcp_port}", auth_token: "#{TOKEN}"
app do |env|
[200, {}, ["Hello World"]]
end
CONF
cli_server "-q -C #{conf_path}", no_bind: true, merge_err: true
out = cli_pumactl_spawn "-F #{conf_path} restart", no_bind: true
assert_includes out.read, "Command restart sent success"
sleep 0.5 # give some time to restart
read_response connect
out = cli_pumactl_spawn "-S #{@state_path} status", no_bind: true
assert_includes out.read, "Puma is started"
end
def test_clustered_stats
skip_unless :fork
skip_unless :unix
min_threads = 1
max_threads = 2
cli_server "-w#{workers} -t#{min_threads}:#{max_threads} -q test/rackup/hello.ru #{set_pumactl_args unix: true} -S #{@state_path}"
worker_pids = get_worker_pids # waits for workers to boot
status = get_stats
assert_equal 2, status["workers"]
sleep 0.5 # needed for GHA ?
stats_hash = get_stats
expected_clustered_root_keys = {
'started_at' => RE_8601,
'workers' => workers,
'phase' => 0,
'booted_workers' => workers,
'old_workers' => 0,
'worker_status' => Array,
'versions' => Hash,
}
assert_hash expected_clustered_root_keys, stats_hash
# worker_status hash
expected_status_hash = {
'started_at' => RE_8601,
'pid' => worker_pids,
'index' => 0...workers,
'phase' => 0,
'booted' => true,
'last_checkin' => RE_8601,
'last_status' => Hash,
}
# worker last_status hash
expected_last_status_hash = {
'backlog' => 0,
'running' => min_threads,
'pool_capacity' => max_threads,
'busy_threads' => 0,
'backlog_max' => 0,
'max_threads' => max_threads,
'requests_count' => 0,
'reactor_max' => 0,
}
pids = []
workers.times do |idx|
worker_hash = stats_hash['worker_status'][idx]
assert_hash expected_status_hash, worker_hash
assert_equal idx, worker_hash['index']
pids << worker_hash['pid']
assert_hash expected_last_status_hash, worker_hash['last_status']
end
assert_equal pids, pids.uniq # no duplicates
#version keys
expected_version_hash = {
'puma' => Puma::Const::VERSION,
'ruby' => Hash,
}
assert_hash expected_version_hash, stats_hash['versions']
#version ruby keys
expected_version_ruby_hash = {
'engine' => RUBY_ENGINE,
'version' => RUBY_VERSION,
'patchlevel' => RUBY_PATCHLEVEL,
}
assert_hash expected_version_ruby_hash, stats_hash['versions']['ruby']
end
def control_gc_stats(unix: false)
cli_server "-t1:1 -q test/rackup/hello.ru #{set_pumactl_args unix: unix} -S #{@state_path}"
key = Puma::IS_MRI ? "count" : "used"
resp_io = cli_pumactl "gc-stats", unix: unix
before = JSON.parse resp_io.read.split("\n", 2).last
gc_before = before[key].to_i
2.times { fast_connect }
resp_io = cli_pumactl "gc", unix: unix
# below shows gc was called (200 reply)
assert_equal "Command gc sent success", resp_io.read.rstrip
resp_io = cli_pumactl "gc-stats", unix: unix
after = JSON.parse resp_io.read.split("\n", 2).last
gc_after = after[key].to_i
# Hitting the /gc route should increment the count by 1
if key == "count"
assert_operator gc_before, :<, gc_after, "make sure a gc has happened"
elsif !Puma::IS_JRUBY
refute_equal gc_before, gc_after, "make sure a gc has happened"
end
end
def test_control_gc_stats_tcp
@control_tcp_port = UniquePort.call
control_gc_stats
end
def test_control_gc_stats_unix
skip_unless :unix
control_gc_stats unix: true
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_integration_single.rb | test/test_integration_single.rb | # frozen_string_literal: true
require_relative "helper"
require_relative "helpers/integration"
class TestIntegrationSingle < TestIntegration
parallelize_me! if ::Puma::IS_MRI
def workers ; 0 ; end
def test_hot_restart_does_not_drop_connections_threads
ttl_reqs = Puma.windows? ? 500 : 1_000
restart_does_not_drop_connections num_threads: 5, total_requests: ttl_reqs,
signal: :USR2
end
def test_hot_restart_does_not_drop_connections
if Puma.windows?
restart_does_not_drop_connections total_requests: 300,
signal: :USR2
else
restart_does_not_drop_connections signal: :USR2
end
end
def test_usr2_restart
skip_unless_signal_exist? :USR2
_, new_reply = restart_server_and_listen("-q test/rackup/hello.ru")
assert_equal "Hello World", new_reply
end
# It does not share environments between multiple generations, which would break Dotenv
def test_usr2_restart_restores_environment
# jruby has a bug where setting `nil` into the ENV or `delete` do not change the
# next workers ENV
skip_if :jruby
skip_unless_signal_exist? :USR2
initial_reply, new_reply = restart_server_and_listen("-q test/rackup/hello-env.ru")
assert_includes initial_reply, "Hello RAND"
assert_includes new_reply, "Hello RAND"
refute_equal initial_reply, new_reply
end
def test_term_exit_code
skip_unless_signal_exist? :TERM
cli_server "test/rackup/hello.ru"
_, status = stop_server
status = status.exitstatus % 128 if ::Puma::IS_JRUBY
assert_equal 15, status
end
def test_after_booted_and_after_stopped
skip_unless_signal_exist? :TERM
cli_server "-C test/config/event_after_booted_and_after_stopped.rb -C test/config/event_after_booted_exit.rb test/rackup/hello.ru",
no_wait: true
assert wait_for_server_to_include('after_booted called')
assert wait_for_server_to_include('after_stopped called')
wait_server 15
end
def test_term_suppress
skip_unless_signal_exist? :TERM
cli_server "-C test/config/suppress_exception.rb test/rackup/hello.ru"
_, status = stop_server
assert_equal 0, status
end
def test_rack_url_scheme_default
skip_unless_signal_exist? :TERM
cli_server("test/rackup/url_scheme.ru")
reply = read_body(connect)
stop_server
assert_match("http", reply)
end
def test_conf_is_loaded_before_passing_it_to_binder
skip_unless_signal_exist? :TERM
cli_server("-C test/config/rack_url_scheme.rb test/rackup/url_scheme.ru")
reply = read_body(connect)
stop_server
assert_match("https", reply)
end
def test_prefer_rackup_file_specified_by_cli
skip_unless_signal_exist? :TERM
cli_server "-C test/config/with_rackup_from_dsl.rb test/rackup/hello.ru"
reply = read_body(connect)
stop_server
assert_match("Hello World", reply)
end
def test_term_not_accepts_new_connections
skip_unless_signal_exist? :TERM
cli_server 'test/rackup/sleep.ru'
_stdin, curl_stdout, _stderr, curl_wait_thread = Open3.popen3({ 'LC_ALL' => 'C' }, "curl http://#{HOST}:#{@tcp_port}/sleep10")
sleep 1 # ensure curl send a request
Process.kill :TERM, @pid
assert wait_for_server_to_include('Gracefully stopping') # wait for server to begin graceful shutdown
# Invoke a request which must be rejected
_stdin, _stdout, rejected_curl_stderr, rejected_curl_wait_thread = Open3.popen3("curl #{HOST}:#{@tcp_port}")
assert nil != Process.getpgid(@server.pid) # ensure server is still running
assert nil != Process.getpgid(curl_wait_thread[:pid]) # ensure first curl invocation still in progress
curl_wait_thread.join
rejected_curl_wait_thread.join
re_curl_error = TRUFFLE ?
/Connection (refused|reset by peer)|(Couldn't|Could not) connect to server/ :
/Connection refused|(Couldn't|Could not) connect to server/
assert_match(/Slept 10/, curl_stdout.read)
assert_match(re_curl_error, rejected_curl_stderr.read)
wait_server 15
end
def test_int_refuse
skip_unless_signal_exist? :INT
cli_server 'test/rackup/hello.ru'
begin
sock = TCPSocket.new(HOST, @tcp_port)
sock.close
rescue => ex
fail("Port didn't open properly: #{ex.message}")
end
Process.kill :INT, @pid
wait_server
assert_raises(Errno::ECONNREFUSED) { TCPSocket.new(HOST, @tcp_port) }
end
def test_siginfo_thread_print
skip_unless_signal_exist? :INFO
cli_server 'test/rackup/hello.ru'
output = []
t = Thread.new { output << @server.readlines }
Process.kill :INFO, @pid
Process.kill :INT , @pid
t.join
assert_match "Thread: TID", output.join
end
def test_write_to_log
skip_unless_signal_exist? :TERM
suppress_output = '> /dev/null 2>&1'
cli_server '-C test/config/t1_conf.rb test/rackup/hello.ru'
system "curl http://localhost:#{@tcp_port}/ #{suppress_output}"
stop_server
log = File.read('t1-stdout')
assert_match(%r!GET / HTTP/1\.1!, log)
ensure
File.unlink 't1-stdout' if File.file? 't1-stdout'
File.unlink 't1-pid' if File.file? 't1-pid'
end
def test_puma_started_log_writing
skip_unless_signal_exist? :TERM
cli_server '-C test/config/t2_conf.rb test/rackup/hello.ru'
system "curl http://localhost:#{@tcp_port}/ > /dev/null 2>&1"
out=`#{BASE} bin/pumactl -F test/config/t2_conf.rb status`
stop_server
log = File.read('t2-stdout')
assert_match(%r!GET / HTTP/1\.1!, log)
assert(!File.file?("t2-pid"))
assert_equal("Puma is started\n", out)
ensure
File.unlink 't2-stdout' if File.file? 't2-stdout'
end
def test_puma_started_log_writing_with_custom_logging
skip_unless_signal_exist? :TERM
cli_server '-C test/config/t4_conf.rb test/rackup/hello.ru'
system "curl http://localhost:#{@tcp_port}/ > /dev/null 2>&1"
out=`#{BASE} bin/pumactl -F test/config/t4_conf.rb status`
stop_server
log = File.read('t4-stdout')
assert_match(%r!Custom logging: 127\.0\.0\.1.*GET / HTTP/1\.1!, log)
assert(!File.file?("t4-pid"))
assert_equal("Puma is started\n", out)
ensure
File.unlink 't4-stdout' if File.file? 't4-stdout'
end
def test_application_logs_are_flushed_on_write
cli_server "#{set_pumactl_args} test/rackup/write_to_stdout.ru"
read_body connect
cli_pumactl 'stop'
assert wait_for_server_to_include("hello\n")
assert wait_for_server_to_include("Goodbye!")
wait_server
end
# listener is closed 'externally' while Puma is in the IO.select statement
def test_closed_listener
skip_unless_signal_exist? :TERM
cli_server "test/rackup/close_listeners.ru", merge_err: true
connection = fast_connect
begin
read_body connection
rescue EOFError
end
begin
Timeout.timeout(5) do
begin
Process.kill :SIGTERM, @pid
rescue Errno::ESRCH
end
begin
Process.wait2 @pid
rescue Errno::ECHILD
end
end
rescue Timeout::Error
Process.kill :SIGKILL, @pid
assert false, "Process froze"
end
assert true
end
def test_puma_debug_loaded_exts
cli_server "#{set_pumactl_args} test/rackup/hello.ru", puma_debug: true
assert wait_for_server_to_include('Loaded Extensions:')
cli_pumactl 'stop'
assert wait_for_server_to_include('Goodbye!')
wait_server
end
def test_idle_timeout
cli_server "test/rackup/hello.ru", config: "idle_timeout 1"
connect
sleep 1.15
assert_raises Errno::ECONNREFUSED, "Connection refused" do
connect
end
end
def test_pre_existing_unix_after_idle_timeout
skip_unless :unix
File.open(@bind_path, mode: 'wb') { |f| f.puts 'pre existing' }
cli_server "-q test/rackup/hello.ru", unix: :unix, config: "idle_timeout 1"
sock = connection = connect(nil, unix: true)
read_body(connection)
sleep 1.15
assert sock.wait_readable(1), 'Unexpected timeout'
assert_raises Puma.jruby? ? IOError : Errno::ECONNREFUSED, "Connection refused" do
connection = connect(nil, unix: true)
end
assert File.exist?(@bind_path)
ensure
if UNIX_SKT_EXIST
File.unlink @bind_path if File.exist? @bind_path
end
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_fiber_local_application.rb | test/test_fiber_local_application.rb | # frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2023, by Samuel Williams.
require_relative "helper"
require "puma/server"
class FiberLocalApplication
def call(env)
# Just in case you didn't know, this is fiber local...
count = (Thread.current[:request_count] ||= 0)
Thread.current[:request_count] += 1
[200, {"Content-Type" => "text/plain"}, [count.to_s]]
end
end
class FiberLocalApplicationTest < PumaTest
parallelize_me!
def setup
@tester = FiberLocalApplication.new
@server = Puma::Server.new @tester, nil, {log_writer: Puma::LogWriter.strings, fiber_per_request: true}
@port = (@server.add_tcp_listener "127.0.0.1", 0).addr[1]
@tcp = "http://127.0.0.1:#{@port}"
@server.run
end
def teardown
@server.stop(true)
end
def test_empty_locals
skip_if :oldwindows
response = hit(["#{@tcp}/test"] * 3)
assert_equal ["0", "0", "0"], response
end
end
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
puma/puma | https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/helper.rb | test/helper.rb | # frozen_string_literal: true
# Copyright (c) 2011 Evan Phoenix
# Copyright (c) 2005 Zed A. Shaw
# WIth GitHub Actions, OS's `/tmp` folder may be on a HDD, while
# ENV['RUNNER_TEMP'] is an SSD. Faster.
if ENV['GITHUB_ACTIONS'] == 'true'
ENV['TMPDIR'] = ENV['RUNNER_TEMP']
end
require "securerandom"
# needs to be loaded before minitest for Ruby 2.7 and earlier
require_relative "helpers/test_puma/assertions"
require_relative "minitest/verbose"
require "minitest/autorun"
require "minitest/pride"
require "minitest/proveit"
require "minitest/stub_const"
require "net/http"
require_relative "helpers/apps"
Thread.abort_on_exception = true
$debugging_info = []
require "puma"
require "puma/detect"
unless ::Puma::HAS_NATIVE_IO_WAIT
require "io/wait"
end
# used in various ssl test files, see test_puma_server_ssl.rb and
# test_puma_localhost_authority.rb
if Puma::HAS_SSL
require 'puma/log_writer'
class SSLLogWriterHelper < ::Puma::LogWriter
attr_accessor :addr, :cert
attr_reader :errors
def error
@errors&.last
end
def ssl_error(error, ssl_socket)
(@errors ||= []) << error
self.addr = ssl_socket.peeraddr.last rescue "<unknown>"
self.cert = ssl_socket.peercert
end
end
end
# Either takes a string to do a get request against, or a tuple of [URI, HTTP] where
# HTTP is some kind of Net::HTTP request object (POST, HEAD, etc.)
def hit(uris)
uris.map do |u|
response =
if u.kind_of? String
Net::HTTP.get(URI.parse(u))
else
url = URI.parse(u[0])
Net::HTTP.new(url.host, url.port).start {|h| h.request(u[1]) }
end
assert response, "Didn't get a response: #{u}"
response
end
end
module UniquePort
def self.call(host = '127.0.0.1')
TCPServer.open(host, 0) do |server|
server.connect_address.ip_port
end
end
end
require "timeout"
module TimeoutPrepend
TEST_CASE_TIMEOUT = ENV.fetch("TEST_CASE_TIMEOUT") do
RUBY_ENGINE == "ruby" ? 45 : 60
end.to_i
# our own subclass so we never confuse different timeouts
class TestTookTooLong < Timeout::Error
end
def capture_exceptions
super do
::Timeout.timeout(TEST_CASE_TIMEOUT, TestTookTooLong) { yield }
end
end
end
Minitest::Test.prepend TimeoutPrepend
class PumaTest < Minitest::Test # rubocop:disable Puma/TestsMustUsePumaTest
def teardown
clean_tmp_paths if respond_to? :clean_tmp_paths
end
end
if ENV['CI']
require 'minitest/retry'
Minitest::Retry::GHA_STEP_SUMMARY_FILE = ENV['GITHUB_STEP_SUMMARY']
Minitest::Retry.use!
if Minitest::Retry::GHA_STEP_SUMMARY_FILE && ENV['GITHUB_ACTIONS'] == 'true'
Minitest::Retry::GHA_STEP_SUMMARY_MUTEX = Mutex.new
Minitest::Retry.on_failure do |klass, test_name, result|
full_method = "#{klass}##{test_name}"
result_str = result.to_s.gsub(/#{full_method}:?\s*/, '').dup
result_str.gsub!(/\A(Failure:|Error:)\s/, '\1 ')
issue = result_str[/\A[^\n]+/]
result_str.gsub!(issue, '')
# shorten directory lists
result_str.gsub! ENV['GITHUB_WORKSPACE'], 'puma'
result_str.gsub! ENV['RUNNER_TOOL_CACHE'], ''
# remove indent
result_str.gsub!(/^ +/, '')
str = "\n**#{full_method}**\n**#{issue}**\n```\n#{result_str.strip}\n```\n"
Minitest::Retry::GHA_STEP_SUMMARY_MUTEX.synchronize {
retry_cntr = 0
begin
File.write Minitest::Retry::GHA_STEP_SUMMARY_FILE, str, mode: 'a+'
rescue IOError # can't write to file, retry once
if retry_cntr == 0
retry_cntr += 1
sleep 0.2
retry
end
end
}
end
end
end
module TestSkips
HAS_FORK = ::Process.respond_to? :fork
UNIX_SKT_EXIST = Object.const_defined?(:UNIXSocket) && !Puma::IS_WINDOWS
MSG_FORK = "Kernel.fork isn't available on #{RUBY_ENGINE} on #{RUBY_PLATFORM}"
MSG_UNIX = "UNIXSockets aren't available on the #{RUBY_PLATFORM} platform"
MSG_AUNIX = "Abstract UNIXSockets aren't available on the #{RUBY_PLATFORM} platform"
SIGNAL_LIST = Signal.list.keys.map(&:to_sym) - (Puma.windows? ? [:INT, :TERM] : [])
JRUBY_HEAD = Puma::IS_JRUBY && RUBY_DESCRIPTION.include?('SNAPSHOT')
DARWIN = RUBY_PLATFORM.include? 'darwin'
TRUFFLE = RUBY_ENGINE == 'truffleruby'
TRUFFLE_HEAD = TRUFFLE && RUBY_DESCRIPTION.include?('-dev-')
# usage: skip_unless_signal_exist? :USR2
def skip_unless_signal_exist?(sig, bt: caller)
signal = sig.to_s.delete_prefix('SIG').to_sym
unless SIGNAL_LIST.include? signal
skip "Signal #{signal} isn't available on the #{RUBY_PLATFORM} platform", bt
end
end
# called with one or more params, like skip_if :jruby, :windows
# optional suffix kwarg is appended to the skip message
# optional suffix bt should generally not used
def skip_if(*engs, suffix: '', bt: caller)
engs.each do |eng|
skip_msg = case eng
when :linux then "Skipped if Linux#{suffix}" if Puma::IS_LINUX
when :darwin then "Skipped if darwin#{suffix}" if Puma::IS_OSX
when :jruby then "Skipped if JRuby#{suffix}" if Puma::IS_JRUBY
when :truffleruby then "Skipped if TruffleRuby#{suffix}" if TRUFFLE
when :windows then "Skipped if Windows#{suffix}" if Puma::IS_WINDOWS
when :ci then "Skipped if ENV['CI']#{suffix}" if ENV['CI']
when :no_bundler then "Skipped w/o Bundler#{suffix}" if !defined?(Bundler)
when :ssl then "Skipped if SSL is supported" if Puma::HAS_SSL
when :fork then "Skipped if Kernel.fork exists" if HAS_FORK
when :unix then "Skipped if UNIXSocket exists" if Puma::HAS_UNIX_SOCKET
when :aunix then "Skipped if abstract UNIXSocket" if Puma.abstract_unix_socket?
when :rack3 then "Skipped if Rack 3.x" if Rack.release >= '3'
when :oldwindows then "Skipped if old Windows" if Puma::IS_WINDOWS && RUBY_VERSION < '2.6'
else false
end
skip skip_msg, bt if skip_msg
end
end
# called with only one param
def skip_unless(eng, bt: caller)
skip_msg = case eng
when :linux then "Skip unless Linux" unless Puma::IS_LINUX
when :darwin then "Skip unless darwin" unless Puma::IS_OSX
when :jruby then "Skip unless JRuby" unless Puma::IS_JRUBY
when :windows then "Skip unless Windows" unless Puma::IS_WINDOWS
when :mri then "Skip unless MRI" unless Puma::IS_MRI
when :ssl then "Skip unless SSL is supported" unless Puma::HAS_SSL
when :fork then MSG_FORK unless HAS_FORK
when :unix then MSG_UNIX unless Puma::HAS_UNIX_SOCKET
when :aunix then MSG_AUNIX unless Puma.abstract_unix_socket?
when :rack3 then "Skipped unless Rack >= 3.x" unless ::Rack.release >= '3'
else false
end
skip skip_msg, bt if skip_msg
end
end
Minitest::Test.include TestSkips
class Minitest::Test
PROJECT_ROOT = File.dirname(__dir__)
def self.run(reporter, options = {}) # :nodoc:
prove_it!
super
end
def full_name
"#{self.class.name}##{name}"
end
end
Minitest.after_run do
if ENV['PUMA_TEST_DEBUG']
$debugging_info.sort!
out = $debugging_info.join.strip
unless out.empty?
dash = "\u2500"
wid = ENV['GITHUB_ACTIONS'] ? 88 : 90
txt = " Debugging Info #{dash * 2}".rjust wid, dash
if ENV['GITHUB_ACTIONS']
puts "", "##[group]#{txt}", out, dash * wid, '', '::[endgroup]'
else
puts "", txt, out, dash * wid, ''
end
end
end
end
module AggregatedResults
def aggregated_results(io)
is_github_actions = ENV['GITHUB_ACTIONS'] == 'true'
filtered_results = results.dup
if options[:verbose]
skips = filtered_results.select(&:skipped?)
unless skips.empty?
dash = "\u2500"
if is_github_actions
puts "", "##[group]Skips:"
else
io.puts '', 'Skips:'
end
hsh = skips.group_by { |f| f.failures.first.error.message }
hsh_s = {}
hsh.each { |k, ary|
hsh_s[k] = ary.map { |s|
[s.source_location, s.klass, s.name]
}.sort_by(&:first)
}
num = 0
hsh_s = hsh_s.sort.to_h
hsh_s.each { |k,v|
io.puts " #{k} #{dash * 2}".rjust 90, dash
hsh_1 = v.group_by { |i| i.first.first }
hsh_1.each { |k1,v1|
io.puts " #{k1[/\/test\/(.*)/,1]}"
v1.each { |item|
num += 1
io.puts format(" %3s %-5s #{item[1]} #{item[2]}", "#{num})", ":#{item[0][1]}")
}
puts ''
}
}
puts '::[endgroup]' if is_github_actions
end
end
filtered_results.reject!(&:skipped?)
io.puts "Errors & Failures:" unless filtered_results.empty?
filtered_results.each_with_index { |result, i|
io.puts "\n%3d) %s" % [i+1, result]
}
io.puts
io
end
end
Minitest::SummaryReporter.prepend AggregatedResults
module TestTempFile
require "tempfile"
def tempfile_create(basename, data, mode: File::BINARY)
fio = Tempfile.create(basename, mode: mode)
fio.write data
fio.flush
fio.rewind
@ios << fio if defined?(@ios)
@ios_to_close << fio if defined?(@ios_to_close)
fio
end
end
Minitest::Test.include TestTempFile
# This module is modified based on https://github.com/rails/rails/blob/7-1-stable/activesupport/lib/active_support/testing/method_call_assertions.rb
module MethodCallAssertions
def assert_called_on_instance_of(klass, method_name, message = nil, times: 1, returns: nil)
times_called = 0
klass.send(:define_method, :"stubbed_#{method_name}") do |*|
times_called += 1
returns
end
klass.send(:alias_method, :"original_#{method_name}", method_name)
klass.send(:alias_method, method_name, :"stubbed_#{method_name}")
yield
error = "Expected #{method_name} to be called #{times} times, but was called #{times_called} times"
error = "#{message}.\n#{error}" if message
assert_equal times, times_called, error
ensure
klass.send(:alias_method, method_name, :"original_#{method_name}")
klass.send(:undef_method, :"original_#{method_name}")
klass.send(:undef_method, :"stubbed_#{method_name}")
end
def assert_not_called_on_instance_of(klass, method_name, message = nil, &block)
assert_called_on_instance_of(klass, method_name, message, times: 0, &block)
end
end
Minitest::Test.include MethodCallAssertions
| ruby | BSD-3-Clause | 5937d8953a154d69cab13887cc361eef9d7df2a4 | 2026-01-04T15:39:19.886485Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.