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
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/remote_token.rb
rack-protection/lib/rack/protection/remote_token.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: CSRF # Supported browsers:: all # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery # # Only accepts unsafe HTTP requests if a given access token matches the token # included in the session *or* the request comes from the same origin. # # Compatible with rack-csrf. class RemoteToken < AuthenticityToken default_reaction :deny def accepts?(env) super or referrer(env) == Request.new(env).host end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/authenticity_token.rb
rack-protection/lib/rack/protection/authenticity_token.rb
# frozen_string_literal: true require 'rack/protection' require 'securerandom' require 'openssl' require 'base64' module Rack module Protection ## # Prevented attack:: CSRF # Supported browsers:: all # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery # # This middleware only accepts requests other than <tt>GET</tt>, # <tt>HEAD</tt>, <tt>OPTIONS</tt>, <tt>TRACE</tt> if their given access # token matches the token included in the session. # # It checks the <tt>X-CSRF-Token</tt> header and the <tt>POST</tt> form # data. # # It is not OOTB-compatible with the {rack-csrf}[https://rubygems.org/gems/rack_csrf] gem. # For that, the following patch needs to be applied: # # Rack::Protection::AuthenticityToken.default_options(key: "csrf.token", authenticity_param: "_csrf") # # == Options # # [<tt>:authenticity_param</tt>] the name of the param that should contain # the token on a request. Default value: # <tt>"authenticity_token"</tt> # # [<tt>:key</tt>] the name of the param that should contain # the token in the session. Default value: # <tt>:csrf</tt> # # [<tt>:allow_if</tt>] a proc for custom allow/deny logic. Default value: # <tt>nil</tt> # # == Example: Forms application # # To show what the AuthenticityToken does, this section includes a sample # program which shows two forms. One with, and one without a CSRF token # The one without CSRF token field will get a 403 Forbidden response. # # Install the gem, then run the program: # # gem install 'rack-protection' # puma server.ru # # Here is <tt>server.ru</tt>: # # require 'rack/protection' # require 'rack/session' # # app = Rack::Builder.app do # use Rack::Session::Cookie, secret: 'CHANGEMEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' # use Rack::Protection::AuthenticityToken # # run -> (env) do # [200, {}, [ # <<~EOS # <!DOCTYPE html> # <html lang="en"> # <head> # <meta charset="UTF-8" /> # <title>rack-protection minimal example</title> # </head> # <body> # <h1>Without Authenticity Token</h1> # <p>This takes you to <tt>Forbidden</tt></p> # <form action="" method="post"> # <input type="text" name="foo" /> # <input type="submit" /> # </form> # # <h1>With Authenticity Token</h1> # <p>This successfully takes you to back to this form.</p> # <form action="" method="post"> # <input type="hidden" name="authenticity_token" value="#{Rack::Protection::AuthenticityToken.token(env['rack.session'])}" /> # <input type="text" name="foo" /> # <input type="submit" /> # </form> # </body> # </html> # EOS # ]] # end # end # # run app # # == Example: Customize which POST parameter holds the token # # To customize the authenticity parameter for form data, use the # <tt>:authenticity_param</tt> option: # use Rack::Protection::AuthenticityToken, authenticity_param: 'your_token_param_name' class AuthenticityToken < Base TOKEN_LENGTH = 32 default_options authenticity_param: 'authenticity_token', key: :csrf, allow_if: nil def self.token(session, path: nil, method: :post) new(nil).mask_authenticity_token(session, path: path, method: method) end def self.random_token SecureRandom.urlsafe_base64(TOKEN_LENGTH, padding: false) end def accepts?(env) session = session(env) set_token(session) safe?(env) || valid_token?(env, env['HTTP_X_CSRF_TOKEN']) || valid_token?(env, Request.new(env).params[options[:authenticity_param]]) || options[:allow_if]&.call(env) rescue StandardError false end def mask_authenticity_token(session, path: nil, method: :post) set_token(session) token = if path && method per_form_token(session, path, method) else global_token(session) end mask_token(token) end GLOBAL_TOKEN_IDENTIFIER = '!real_csrf_token' private_constant :GLOBAL_TOKEN_IDENTIFIER private def set_token(session) session[options[:key]] ||= self.class.random_token end # Checks the client's masked token to see if it matches the # session token. def valid_token?(env, token) return false if token.nil? || !token.is_a?(String) || token.empty? session = session(env) begin token = decode_token(token) rescue ArgumentError # encoded_masked_token is invalid Base64 return false end # See if it's actually a masked token or not. We should be able # to handle any unmasked tokens that we've issued without error. if unmasked_token?(token) compare_with_real_token(token, session) elsif masked_token?(token) token = unmask_token(token) compare_with_global_token(token, session) || compare_with_real_token(token, session) || compare_with_per_form_token(token, session, Request.new(env)) else false # Token is malformed end end # Creates a masked version of the authenticity token that varies # on each request. The masking is used to mitigate SSL attacks # like BREACH. def mask_token(token) one_time_pad = SecureRandom.random_bytes(token.length) encrypted_token = xor_byte_strings(one_time_pad, token) masked_token = one_time_pad + encrypted_token encode_token(masked_token) end # Essentially the inverse of +mask_token+. def unmask_token(masked_token) # Split the token into the one-time pad and the encrypted # value and decrypt it token_length = masked_token.length / 2 one_time_pad = masked_token[0...token_length] encrypted_token = masked_token[token_length..] xor_byte_strings(one_time_pad, encrypted_token) end def unmasked_token?(token) token.length == TOKEN_LENGTH end def masked_token?(token) token.length == TOKEN_LENGTH * 2 end def compare_with_real_token(token, session) secure_compare(token, real_token(session)) end def compare_with_global_token(token, session) secure_compare(token, global_token(session)) end def compare_with_per_form_token(token, session, request) secure_compare(token, per_form_token(session, request.path.chomp('/'), request.request_method)) end def real_token(session) decode_token(session[options[:key]]) end def global_token(session) token_hmac(session, GLOBAL_TOKEN_IDENTIFIER) end def per_form_token(session, path, method) token_hmac(session, "#{path}##{method.downcase}") end def encode_token(token) Base64.urlsafe_encode64(token) end def decode_token(token) Base64.urlsafe_decode64(token) end def token_hmac(session, identifier) OpenSSL::HMAC.digest( OpenSSL::Digest.new('SHA256'), real_token(session), identifier ) end def xor_byte_strings(s1, s2) s2 = s2.dup size = s1.bytesize i = 0 while i < size s2.setbyte(i, s1.getbyte(i) ^ s2.getbyte(i)) i += 1 end s2 end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/version.rb
rack-protection/lib/rack/protection/version.rb
# frozen_string_literal: true module Rack module Protection VERSION = '4.2.1' end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/form_token.rb
rack-protection/lib/rack/protection/form_token.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: CSRF # Supported browsers:: all # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery # # Only accepts submitted forms if a given access token matches the token # included in the session. Does not expect such a token from Ajax request. # # This middleware is not used when using the Rack::Protection collection, # since it might be a security issue, depending on your application # # Compatible with rack-csrf. class FormToken < AuthenticityToken def accepts?(env) env['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' or super end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/path_traversal.rb
rack-protection/lib/rack/protection/path_traversal.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: Directory traversal # Supported browsers:: all # More infos:: http://en.wikipedia.org/wiki/Directory_traversal # # Unescapes '/' and '.', expands +path_info+. # Thus <tt>GET /foo/%2e%2e%2fbar</tt> becomes <tt>GET /bar</tt>. class PathTraversal < Base def call(env) path_was = env['PATH_INFO'] env['PATH_INFO'] = cleanup path_was if path_was && !path_was.empty? app.call env ensure env['PATH_INFO'] = path_was end def cleanup(path) encoding = path.encoding dot = '.'.encode(encoding) slash = '/'.encode(encoding) backslash = '\\'.encode(encoding) parts = [] unescaped = path.gsub(/%2e/i, dot).gsub(/%2f/i, slash).gsub(/%5c/i, backslash) unescaped = unescaped.gsub(backslash, slash) unescaped.split(slash).each do |part| next if part.empty? || (part == dot) part == '..' ? parts.pop : parts << part end cleaned = slash + parts.join(slash) cleaned << slash if parts.any? && unescaped =~ (%r{/\.{0,2}$}) cleaned end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/json_csrf.rb
rack-protection/lib/rack/protection/json_csrf.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: CSRF # Supported browsers:: all # More infos:: http://flask.pocoo.org/docs/0.10/security/#json-security # http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx # # JSON GET APIs are vulnerable to being embedded as JavaScript when the # Array prototype has been patched to track data. Checks the referrer # even on GET requests if the content type is JSON. # # If request includes Origin HTTP header, defers to HttpOrigin to determine # if the request is safe. Please refer to the documentation for more info. # # The `:allow_if` option can be set to a proc to use custom allow/deny logic. class JsonCsrf < Base default_options allow_if: nil alias react deny def call(env) request = Request.new(env) status, headers, body = app.call(env) if has_vector?(request, headers) warn env, "attack prevented by #{self.class}" react_and_close(env, body) or [status, headers, body] else [status, headers, body] end end def has_vector?(request, headers) return false if request.xhr? return false if options[:allow_if]&.call(request.env) return false unless headers['content-type'].to_s.split(';', 2).first =~ %r{^\s*application/json\s*$} origin(request.env).nil? and referrer(request.env) != request.host end def react_and_close(env, body) reaction = react(env) close_body(body) if reaction reaction end def close_body(body) body.close if body.respond_to?(:close) end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/escaped_params.rb
rack-protection/lib/rack/protection/escaped_params.rb
# frozen_string_literal: true require 'rack/protection' require 'rack/utils' require 'tempfile' begin require 'escape_utils' rescue LoadError end module Rack module Protection ## # Prevented attack:: XSS # Supported browsers:: all # More infos:: http://en.wikipedia.org/wiki/Cross-site_scripting # # Automatically escapes Rack::Request#params so they can be embedded in HTML # or JavaScript without any further issues. # # Options: # escape:: What escaping modes to use, should be Symbol or Array of Symbols. # Available: :html (default), :javascript, :url class EscapedParams < Base extend Rack::Utils class << self alias escape_url escape public :escape_html end default_options escape: :html, escaper: defined?(EscapeUtils) ? EscapeUtils : self def initialize(*) super modes = Array options[:escape] @escaper = options[:escaper] @html = modes.include? :html @javascript = modes.include? :javascript @url = modes.include? :url return unless @javascript && (!@escaper.respond_to? :escape_javascript) raise('Use EscapeUtils for JavaScript escaping.') end def call(env) request = Request.new(env) get_was = handle(request.GET) post_was = begin handle(request.POST) rescue StandardError nil end app.call env ensure request.GET.replace get_was if get_was request.POST.replace post_was if post_was end def handle(hash) was = hash.dup hash.replace escape(hash) was end def escape(object) case object when Hash then escape_hash(object) when Array then object.map { |o| escape(o) } when String then escape_string(object) when Tempfile then object end end def escape_hash(hash) hash = hash.dup hash.each { |k, v| hash[k] = escape(v) } hash end def escape_string(str) str = @escaper.escape_url(str) if @url str = @escaper.escape_html(str) if @html str = @escaper.escape_javascript(str) if @javascript str end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/base.rb
rack-protection/lib/rack/protection/base.rb
# frozen_string_literal: true require 'rack/protection' require 'rack/utils' require 'digest' require 'logger' require 'uri' module Rack module Protection class Base DEFAULT_OPTIONS = { reaction: :default_reaction, logging: true, message: 'Forbidden', encryptor: Digest::SHA1, session_key: 'rack.session', status: 403, allow_empty_referrer: true, report_key: 'protection.failed', html_types: %w[text/html application/xhtml text/xml application/xml] } attr_reader :app, :options def self.default_options(options) define_method(:default_options) { super().merge(options) } end def self.default_reaction(reaction) alias_method(:default_reaction, reaction) end def default_options DEFAULT_OPTIONS end def initialize(app, options = {}) @app = app @options = default_options.merge(options) end def safe?(env) %w[GET HEAD OPTIONS TRACE].include? env['REQUEST_METHOD'] end def accepts?(env) raise NotImplementedError, "#{self.class} implementation pending" end def call(env) unless accepts? env instrument env result = react env end result or app.call(env) end def react(env) result = send(options[:reaction], env) result if (Array === result) && (result.size == 3) end def debug(env, message) return unless options[:logging] l = options[:logger] || env['rack.logger'] || ::Logger.new(env['rack.errors']) l.debug(message) end def warn(env, message) return unless options[:logging] l = options[:logger] || env['rack.logger'] || ::Logger.new(env['rack.errors']) l.warn(message) end def instrument(env) return unless (i = options[:instrumenter]) env['rack.protection.attack'] = self.class.name.split('::').last.downcase i.instrument('rack.protection', env) end def deny(env) warn env, "attack prevented by #{self.class}" [options[:status], { 'content-type' => 'text/plain' }, [options[:message]]] end def report(env) warn env, "attack reported by #{self.class}" env[options[:report_key]] = true end def session?(env) env.include? options[:session_key] end def session(env) return env[options[:session_key]] if session? env raise "you need to set up a session middleware *before* #{self.class}" end def drop_session(env) return unless session? env session(env).clear return if ["1", "true"].include?(ENV["RACK_PROTECTION_SILENCE_DROP_SESSION_WARNING"]) warn env, "session dropped by #{self.class}" end def referrer(env) ref = env['HTTP_REFERER'].to_s return if !options[:allow_empty_referrer] && ref.empty? URI.parse(ref).host || Request.new(env).host rescue URI::InvalidURIError end def origin(env) env['HTTP_ORIGIN'] || env['HTTP_X_ORIGIN'] end def random_string(secure = defined? SecureRandom) secure ? SecureRandom.hex(16) : '%032x' % rand((2**128) - 1) rescue NotImplementedError random_string false end def encrypt(value) options[:encryptor].hexdigest value.to_s end def secure_compare(a, b) Rack::Utils.secure_compare(a.to_s, b.to_s) end alias default_reaction deny def html?(headers) return false unless (header = headers.detect { |k, _v| k.downcase == 'content-type' }) options[:html_types].include? header.last[%r{^\w+/\w+}] end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/strict_transport.rb
rack-protection/lib/rack/protection/strict_transport.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: Protects against against protocol downgrade attacks and cookie hijacking. # Supported browsers:: all # More infos:: https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security # # browser will prevent any communications from being sent over HTTP # to the specified domain and will instead send all communications over HTTPS. # It also prevents HTTPS click through prompts on browsers. # # Options: # # max_age:: How long future requests to the domain should go over HTTPS; specified in seconds # include_subdomains:: If all present and future subdomains will be HTTPS # preload:: Allow this domain to be included in browsers HSTS preload list. See https://hstspreload.appspot.com/ class StrictTransport < Base default_options max_age: 31_536_000, include_subdomains: false, preload: false def strict_transport @strict_transport ||= begin strict_transport = "max-age=#{options[:max_age]}" strict_transport += '; includeSubDomains' if options[:include_subdomains] strict_transport += '; preload' if options[:preload] strict_transport.to_str end end def call(env) status, headers, body = @app.call(env) headers['strict-transport-security'] ||= strict_transport [status, headers, body] end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/http_origin.rb
rack-protection/lib/rack/protection/http_origin.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: CSRF # Supported browsers:: Google Chrome 2, Safari 4 and later # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery # http://tools.ietf.org/html/draft-abarth-origin # # Does not accept unsafe HTTP requests when value of Origin HTTP request header # does not match default or permitted URIs. # # If you want to permit a specific domain, you can pass in as the `:permitted_origins` option: # # use Rack::Protection, permitted_origins: ["http://localhost:3000", "http://127.0.01:3000"] # # The `:allow_if` option can also be set to a proc to use custom allow/deny logic. class HttpOrigin < Base DEFAULT_PORTS = { 'http' => 80, 'https' => 443, 'coffee' => 80 } default_reaction :deny default_options allow_if: nil def base_url(env) request = Rack::Request.new(env) port = ":#{request.port}" unless request.port == DEFAULT_PORTS[request.scheme] "#{request.scheme}://#{request.host}#{port}" end def accepts?(env) return true if safe? env return true unless (origin = env['HTTP_ORIGIN']) return true if base_url(env) == origin return true if options[:allow_if]&.call(env) permitted_origins = options[:permitted_origins] Array(permitted_origins).include? origin end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/remote_referrer.rb
rack-protection/lib/rack/protection/remote_referrer.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: CSRF # Supported browsers:: all # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery # # Does not accept unsafe HTTP requests if the Referer [sic] header is set to # a different host. class RemoteReferrer < Base default_reaction :deny def accepts?(env) safe?(env) or referrer(env) == Request.new(env).host end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/session_hijacking.rb
rack-protection/lib/rack/protection/session_hijacking.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: Session Hijacking # Supported browsers:: all # More infos:: http://en.wikipedia.org/wiki/Session_hijacking # # Tracks request properties like the user agent in the session and empties # the session if those properties change. This essentially prevents attacks # from Firesheep. Since all headers taken into consideration can be # spoofed, too, this will not prevent determined hijacking attempts. class SessionHijacking < Base default_reaction :drop_session default_options tracking_key: :tracking, track: %w[HTTP_USER_AGENT] def accepts?(env) session = session env key = options[:tracking_key] if session.include? key session[key].all? { |k, v| v == encode(env[k]) } else session[key] = {} options[:track].each { |k| session[key][k] = encode(env[k]) } end end def encode(value) value.to_s.downcase end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/xss_header.rb
rack-protection/lib/rack/protection/xss_header.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: Non-permanent XSS # Supported browsers:: Internet Explorer 8+ and Chrome # More infos:: http://blogs.msdn.com/b/ie/archive/2008/07/01/ie8-security-part-iv-the-xss-filter.aspx # # Sets X-XSS-Protection header to tell the browser to block attacks. # # Options: # xss_mode:: How the browser should prevent the attack (default: :block) class XSSHeader < Base default_options xss_mode: :block, nosniff: true def call(env) status, headers, body = @app.call(env) headers['x-xss-protection'] ||= "1; mode=#{options[:xss_mode]}" if html? headers headers['x-content-type-options'] ||= 'nosniff' if options[:nosniff] [status, headers, body] end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/ip_spoofing.rb
rack-protection/lib/rack/protection/ip_spoofing.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: IP spoofing # Supported browsers:: all # More infos:: http://blog.c22.cc/2011/04/22/surveymonkey-ip-spoofing/ # # Detect (some) IP spoofing attacks. class IPSpoofing < Base default_reaction :deny def accepts?(env) return true unless env.include? 'HTTP_X_FORWARDED_FOR' ips = env['HTTP_X_FORWARDED_FOR'].split(',').map(&:strip) return false if env.include?('HTTP_CLIENT_IP') && (!ips.include? env['HTTP_CLIENT_IP']) return false if env.include?('HTTP_X_REAL_IP') && (!ips.include? env['HTTP_X_REAL_IP']) true end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/frame_options.rb
rack-protection/lib/rack/protection/frame_options.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: Clickjacking # Supported browsers:: Internet Explorer 8, Firefox 3.6.9, Opera 10.50, # Safari 4.0, Chrome 4.1.249.1042 and later # More infos:: https://developer.mozilla.org/en/The_X-FRAME-OPTIONS_response_header # # Sets X-Frame-Options header to tell the browser avoid embedding the page # in a frame. # # Options: # # frame_options:: Defines who should be allowed to embed the page in a # frame. Use :deny to forbid any embedding, :sameorigin # to allow embedding from the same origin (default). class FrameOptions < Base default_options frame_options: :sameorigin def frame_options @frame_options ||= begin frame_options = options[:frame_options] frame_options = options[:frame_options].to_s.upcase unless frame_options.respond_to? :to_str frame_options.to_str end end def call(env) status, headers, body = @app.call(env) headers['x-frame-options'] ||= frame_options if html? headers [status, headers, body] end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/referrer_policy.rb
rack-protection/lib/rack/protection/referrer_policy.rb
# frozen_string_literal: true require 'rack/protection' module Rack module Protection ## # Prevented attack:: Secret leakage, third party tracking # Supported browsers:: mixed support # More infos:: https://www.w3.org/TR/referrer-policy/ # https://caniuse.com/#search=referrer-policy # # Sets Referrer-Policy header to tell the browser to limit the Referer header. # # Options: # referrer_policy:: The policy to use (default: 'strict-origin-when-cross-origin') class ReferrerPolicy < Base default_options referrer_policy: 'strict-origin-when-cross-origin' def call(env) status, headers, body = @app.call(env) headers['referrer-policy'] ||= options[:referrer_policy] [status, headers, body] end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/rack-protection/lib/rack/protection/host_authorization.rb
rack-protection/lib/rack/protection/host_authorization.rb
# frozen_string_literal: true require 'rack/protection' require 'ipaddr' module Rack module Protection ## # Prevented attack:: DNS rebinding and other Host header attacks # Supported browsers:: all # More infos:: https://en.wikipedia.org/wiki/DNS_rebinding # https://portswigger.net/web-security/host-header # # Blocks HTTP requests with an unrecognized hostname in any of the following # HTTP headers: Host, X-Forwarded-Host, Forwarded # # If you want to permit a specific hostname, you can pass in as the `:permitted_hosts` option: # # use Rack::Protection::HostAuthorization, permitted_hosts: ["www.example.org", "sinatrarb.com"] # # The `:allow_if` option can also be set to a proc to use custom allow/deny logic. class HostAuthorization < Base DOT = '.' PORT_REGEXP = /:\d+\z/.freeze SUBDOMAINS = /[a-z0-9\-.]+/.freeze private_constant :DOT, :PORT_REGEXP, :SUBDOMAINS default_reaction :deny default_options allow_if: nil, message: 'Host not permitted' def initialize(*) super @permitted_hosts = [] @domain_hosts = [] @ip_hosts = [] @all_permitted_hosts = Array(options[:permitted_hosts]) @all_permitted_hosts.each do |host| case host when String if host.start_with?(DOT) domain = host[1..-1] @permitted_hosts << domain.downcase @domain_hosts << /\A#{SUBDOMAINS}#{Regexp.escape(domain)}\z/i else @permitted_hosts << host.downcase end when IPAddr then @ip_hosts << host end end end def accepts?(env) return true if options[:allow_if]&.call(env) return true if @all_permitted_hosts.empty? request = Request.new(env) origin_host = extract_host(request.host_authority) forwarded_host = extract_host(request.forwarded_authority) debug env, "#{self.class} " \ "@all_permitted_hosts=#{@all_permitted_hosts.inspect} " \ "@permitted_hosts=#{@permitted_hosts.inspect} " \ "@domain_hosts=#{@domain_hosts.inspect} " \ "@ip_hosts=#{@ip_hosts.inspect} " \ "origin_host=#{origin_host.inspect} " \ "forwarded_host=#{forwarded_host.inspect}" if host_permitted?(origin_host) if forwarded_host.nil? true else host_permitted?(forwarded_host) end else false end end private def extract_host(authority) authority.to_s.split(PORT_REGEXP).first&.downcase end def host_permitted?(host) exact_match?(host) || domain_match?(host) || ip_match?(host) end def exact_match?(host) @permitted_hosts.include?(host) end def domain_match?(host) return false if host.nil? return false if host.start_with?(DOT) @domain_hosts.any? { |domain_host| host.match?(domain_host) } end def ip_match?(host) @ip_hosts.any? { |ip_host| ip_host.include?(host) } rescue IPAddr::InvalidAddressError false end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/integration_test.rb
test/integration_test.rb
require_relative 'test_helper' require File.expand_path('integration_helper', __dir__) # These tests start a real server and talk to it over TCP. # Every test runs with every detected server. # # See test/integration/app.rb for the code of the app we test against. class IntegrationTest < Minitest::Test extend IntegrationHelper attr_accessor :server it('sets the app_file') { assert_equal server.app_file, server.get("/app_file") } it('only extends main') { assert_equal "true", server.get("/mainonly") } it 'logs once in development mode' do next if server.puma? or server.falcon? or RUBY_ENGINE == 'jruby' random = "%064x" % Kernel.rand(2**256-1) server.get "/ping?x=#{random}" count = server.log.scan("GET /ping?x=#{random}").count if server.net_http_server? assert_equal 0, count elsif server.webrick? assert(count > 0) else assert_equal(1, count) end end it 'streams' do next if server.webrick? or server.trinidad? times, chunks = [Process.clock_gettime(Process::CLOCK_MONOTONIC)], [] server.get_stream do |chunk| next if chunk.empty? chunks << chunk times << Process.clock_gettime(Process::CLOCK_MONOTONIC) end assert_equal ["a", "b"], chunks int1 = (times[1] - times[0]).round 2 int2 = (times[2] - times[1]).round 2 assert_operator 1, :>, int1 assert_operator 1, :<, int2 end it 'starts the correct server' do exp = %r{ ==\sSinatra\s\(v#{Sinatra::VERSION}\)\s has\staken\sthe\sstage\son\s\d+\sfor\sdevelopment\s with\sbackup\sfrom\s#{server} }ix # because Net HTTP Server logs to $stderr by default assert_match exp, server.log unless server.net_http_server? end it 'does not generate warnings' do assert_raises(OpenURI::HTTPError) { server.get '/' } server.get '/app_file' assert_equal [], server.warnings end it 'sets the Content-Length response header when sending files' do response = server.get_response '/send_file' assert response['Content-Length'] end it "doesn't ignore Content-Length header when streaming" do response = server.get_response '/streaming' assert_equal '46', response['Content-Length'] end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/asciidoctor_test.rb
test/asciidoctor_test.rb
require_relative 'test_helper' begin require 'asciidoctor' class AsciidoctorTest < Minitest::Test def asciidoc_app(&block) mock_app do set :views, __dir__ + '/views' get('/', &block) end get '/' end it 'renders inline AsciiDoc strings' do asciidoc_app { asciidoc '== Hiya' } assert ok? assert_match %r{<h2.*?>Hiya</h2>}, body end it 'uses the correct engine' do engine = Tilt::AsciidoctorTemplate assert_equal engine, Tilt[:ad] assert_equal engine, Tilt[:adoc] assert_equal engine, Tilt[:asciidoc] end it 'renders .asciidoc files in views path' do asciidoc_app { asciidoc :hello } assert ok? assert_match %r{<h2.*?>Hello from AsciiDoc</h2>}, body end it 'raises error if template not found' do mock_app { get('/') { asciidoc :no_such_template } } assert_raises(Errno::ENOENT) { get('/') } end it 'renders with inline layouts' do mock_app do layout { 'THIS. IS. #{yield.upcase}!' } get('/') { asciidoc 'Sparta', :layout_engine => :str } end get '/' assert ok? assert_include body, 'THIS. IS.' assert_include body, '<P>SPARTA</P>' end it 'renders with file layouts' do asciidoc_app do asciidoc 'Hello World', :layout => :layout2, :layout_engine => :erb end assert ok? assert_include body, 'ERB Layout!' assert_include body, '<p>Hello World</p>' end it 'can be used in a nested fashion for partials and whatnot' do mock_app do template(:inner) { 'hi' } template(:outer) { '<outer><%= asciidoc :inner %></outer>' } get('/') { erb :outer } end get '/' assert ok? assert_match %r{<outer>.*<p.*?>hi</p>.*</outer>}m, body end end rescue LoadError warn "#{$!}: skipping asciidoc tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/sinatra_test.rb
test/sinatra_test.rb
require_relative 'test_helper' class SinatraTest < Minitest::Test it 'creates a new Sinatra::Base subclass on new' do app = Sinatra.new { get('/') { 'Hello World' } } assert_same Sinatra::Base, app.superclass end it "responds to #template_cache" do assert_kind_of Sinatra::TemplateCache, Sinatra::Base.new!.template_cache end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/rack_test.rb
test/rack_test.rb
require_relative 'test_helper' require 'rack' class RackTest < Minitest::Test setup do @foo = Sinatra.new { get('/foo') { 'foo' }} @bar = Sinatra.new { get('/bar') { 'bar' }} end def build(*middleware) endpoint = middleware.pop @app = Rack::Builder.app do middleware.each { |m| use m } run endpoint end end def check(*middleware) build(*middleware) assert get('/foo').ok? assert_body 'foo' assert get('/bar').ok? assert_body 'bar' end it 'works as middleware in front of Rack::Lock, with lock enabled' do @foo.enable :lock check(@foo, Rack::Lock, @bar) end it 'works as middleware behind Rack::Lock, with lock enabled' do @foo.enable :lock check(Rack::Lock, @foo, @bar) end it 'works as middleware in front of Rack::Lock, with lock disabled' do @foo.disable :lock check(@foo, Rack::Lock, @bar) end it 'works as middleware behind Rack::Lock, with lock disabled' do @foo.disable :lock check(Rack::Lock, @foo, @bar) end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/indifferent_hash_test.rb
test/indifferent_hash_test.rb
# frozen_string_literal: true # # We don't need the full test helper for this standalone class. # require 'minitest/autorun' unless defined?(Minitest) require_relative '../lib/sinatra/indifferent_hash' class TestIndifferentHashBasics < Minitest::Test def test_flattened_constructor hash = Sinatra::IndifferentHash[:a, 1, ?b, 2] assert_equal 1, hash[?a] assert_equal 2, hash[?b] end def test_pairs_constructor hash = Sinatra::IndifferentHash[[[:a, 1], [?b, 2]]] assert_equal 1, hash[?a] assert_equal 2, hash[?b] end def test_default_block hash = Sinatra::IndifferentHash.new { |h, k| h[k] = k.upcase } assert_nil hash.default assert_equal ?A, hash.default(:a) end def test_default_object hash = Sinatra::IndifferentHash.new({:a=>1, ?b=>2}) assert_equal({ :a=>1, ?b=>2 }, hash.default) assert_equal({ :a=>1, ?b=>2 }, hash[:a]) end def test_default_assignment hash = Sinatra::IndifferentHash.new hash.default = { :a=>1, ?b=>2 } assert_equal({ ?a=>1, ?b=>2 }, hash.default) assert_equal({ ?a=>1, ?b=>2 }, hash[:a]) end def test_assignment hash = Sinatra::IndifferentHash.new hash[:a] = :a hash[?b] = :b hash[3] = 3 hash[:simple_nested] = { :a=>:a, ?b=>:b } assert_equal :a, hash[?a] assert_equal :b, hash[?b] assert_equal 3, hash[3] assert_equal({ ?a=>:a, ?b=>:b }, hash['simple_nested']) assert_nil hash[?d] end def test_merge! # merge! is already mostly tested by the different constructors, so we # really just need to test the block form here hash = Sinatra::IndifferentHash[:a=>'a', ?b=>'b', 3=>3] hash.merge!(?a=>'A', :b=>'B', :d=>'D') do |key, oldval, newval| "#{oldval}*#{key}*#{newval}" end assert_equal({ ?a=>'a*a*A', ?b=>'b*b*B', 3=>3, ?d=>'D' }, hash) end end class TestIndifferentHash < Minitest::Test def setup @hash = Sinatra::IndifferentHash[:a=>:a, ?b=>:b, 3=>3, :simple_nested=>{ :a=>:a, ?b=>:b }, :nested=>{ :a=>[{ :a=>:a, ?b=>:b }, :c, 4], ?f=>:f, 7=>7 } ] end def test_hash_constructor assert_equal :a, @hash[?a] assert_equal :b, @hash[?b] assert_equal 3, @hash[3] assert_equal({ ?a=>:a, ?b=>:b }, @hash['nested'][?a][0]) assert_equal :c, @hash['nested'][?a][1] assert_equal 4, @hash['nested'][?a][2] assert_equal :f, @hash['nested'][?f] assert_equal 7, @hash['nested'][7] assert_equal :a, @hash['simple_nested'][?a] assert_equal :b, @hash['simple_nested'][?b] assert_nil @hash[?d] end def test_assoc assert_nil @hash.assoc(:d) assert_equal [?a, :a], @hash.assoc(:a) assert_equal [?b, :b], @hash.assoc(:b) end def test_rassoc assert_nil @hash.rassoc(:d) assert_equal [?a, :a], @hash.rassoc(:a) assert_equal [?b, :b], @hash.rassoc(:b) assert_equal ['simple_nested', { ?a=>:a, ?b=>:b }], @hash.rassoc(:a=>:a, ?b=>:b) end def test_fetch assert_raises(KeyError) { @hash.fetch(:d) } assert_equal 1, @hash.fetch(:d, 1) assert_equal 2, @hash.fetch(:d) { 2 } assert_equal ?d, @hash.fetch(:d) { |k| k } assert_equal :a, @hash.fetch(:a, 1) assert_equal :a, @hash.fetch(:a) { 2 } end def test_symbolic_retrieval assert_equal :a, @hash[:a] assert_equal :b, @hash[:b] assert_equal({ ?a=>:a, ?b=>:b }, @hash[:nested][:a][0]) assert_equal :c, @hash[:nested][:a][1] assert_equal 4, @hash[:nested][:a][2] assert_equal :f, @hash[:nested][:f] assert_equal 7, @hash[:nested][7] assert_equal :a, @hash[:simple_nested][:a] assert_equal :b, @hash[:simple_nested][:b] assert_nil @hash[:d] end def test_key assert_nil @hash.key(:d) assert_equal ?a, @hash.key(:a) assert_equal 'simple_nested', @hash.key(:a=>:a, ?b=>:b) end def test_key? assert_operator @hash, :key?, :a assert_operator @hash, :key?, ?b assert_operator @hash, :key?, 3 refute_operator @hash, :key?, :d end def test_value? assert_operator @hash, :value?, :a assert_operator @hash, :value?, :b assert_operator @hash, :value?, 3 assert_operator @hash, :value?, { :a=>:a, ?b=>:b } refute_operator @hash, :value?, :d end def test_delete @hash.delete(:a) @hash.delete(?b) assert_nil @hash[:a] assert_nil @hash[?b] end def test_dig assert_equal :a, @hash.dig(:a) assert_equal :b, @hash.dig(?b) assert_nil @hash.dig(:d) assert_equal :a, @hash.dig(:simple_nested, :a) assert_equal :b, @hash.dig('simple_nested', ?b) assert_nil @hash.dig('simple_nested', :d) assert_equal :a, @hash.dig(:nested, :a, 0, :a) assert_equal :b, @hash.dig('nested', ?a, 0, ?b) assert_nil @hash.dig('nested', ?a, 0, :d) end def test_slice assert_equal Sinatra::IndifferentHash[a: :a], @hash.slice(:a) assert_equal Sinatra::IndifferentHash[b: :b], @hash.slice(?b) assert_equal Sinatra::IndifferentHash[3 => 3], @hash.slice(3) assert_equal Sinatra::IndifferentHash.new, @hash.slice(:d) assert_equal Sinatra::IndifferentHash[a: :a, b: :b, 3 => 3], @hash.slice(:a, :b, 3) assert_equal Sinatra::IndifferentHash[simple_nested: { a: :a, ?b => :b }], @hash.slice(:simple_nested) assert_equal Sinatra::IndifferentHash[nested: { a: [{ a: :a, ?b => :b }, :c, 4], ?f => :f, 7 => 7 }], @hash.slice(:nested) end def test_fetch_values assert_raises(KeyError) { @hash.fetch_values(3, :d) } assert_equal [:a, :b, 3, ?D], @hash.fetch_values(:a, ?b, 3, :d) { |k| k.upcase } end def test_values_at assert_equal [:a, :b, 3, nil], @hash.values_at(:a, ?b, 3, :d) end def test_merge # merge just calls merge!, which is already thoroughly tested hash2 = @hash.merge(?a=>1, :q=>2) { |key, oldval, newval| "#{oldval}*#{key}*#{newval}" } refute_equal @hash, hash2 assert_equal 'a*a*1', hash2[:a] assert_equal 2, hash2[?q] end def test_merge_with_multiple_argument hash = Sinatra::IndifferentHash.new.merge({a: 1}, {b: 2}, {c: 3}) assert_equal 1, hash[?a] assert_equal 2, hash[?b] assert_equal 3, hash[?c] hash2 = Sinatra::IndifferentHash[d: 4] hash3 = {e: 5} hash.merge!(hash2, hash3) assert_equal 4, hash[?d] assert_equal 5, hash[?e] end def test_replace @hash.replace(?a=>1, :q=>2) assert_equal({ ?a=>1, ?q=>2 }, @hash) end def test_transform_values! @hash.transform_values! { |v| v.is_a?(Hash) ? Hash[v.to_a] : v } assert_instance_of Sinatra::IndifferentHash, @hash[:simple_nested] end def test_transform_values hash2 = @hash.transform_values { |v| v.respond_to?(:upcase) ? v.upcase : v } refute_equal @hash, hash2 assert_equal :A, hash2[:a] assert_equal :A, hash2[?a] end def test_transform_keys! @hash.transform_keys! { |k| k.respond_to?(:to_sym) ? k.to_sym : k } assert_equal :a, @hash[:a] assert_equal :a, @hash[?a] end def test_transform_keys hash2 = @hash.transform_keys { |k| k.respond_to?(:upcase) ? k.upcase : k } refute_equal @hash, hash2 refute_operator hash2, :key?, :a refute_operator hash2, :key?, ?a assert_equal :a, hash2[:A] assert_equal :a, hash2[?A] end def test_select hash = @hash.select { |k, v| v == :a } assert_equal Sinatra::IndifferentHash[a: :a], hash assert_instance_of Sinatra::IndifferentHash, hash hash2 = @hash.select { |k, v| true } assert_equal @hash, hash2 assert_instance_of Sinatra::IndifferentHash, hash2 enum = @hash.select assert_instance_of Enumerator, enum end def test_select! @hash.select! { |k, v| v == :a } assert_equal Sinatra::IndifferentHash[a: :a], @hash end def test_reject hash = @hash.reject { |k, v| v != :a } assert_equal Sinatra::IndifferentHash[a: :a], hash assert_instance_of Sinatra::IndifferentHash, hash hash2 = @hash.reject { |k, v| false } assert_equal @hash, hash2 assert_instance_of Sinatra::IndifferentHash, hash2 enum = @hash.reject assert_instance_of Enumerator, enum end def test_reject! @hash.reject! { |k, v| v != :a } assert_equal Sinatra::IndifferentHash[a: :a], @hash end def test_compact hash_with_nil_values = @hash.merge({?z => nil}) compacted_hash = hash_with_nil_values.compact assert_equal @hash, compacted_hash assert_instance_of Sinatra::IndifferentHash, compacted_hash empty_hash = Sinatra::IndifferentHash.new compacted_hash = empty_hash.compact assert_equal empty_hash, compacted_hash non_empty_hash = Sinatra::IndifferentHash[a: :a] compacted_hash = non_empty_hash.compact assert_equal non_empty_hash, compacted_hash end def test_except hash = @hash.except(?b, 3, :simple_nested, 'nested') assert_equal Sinatra::IndifferentHash[a: :a], hash assert_instance_of Sinatra::IndifferentHash, hash end if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("3.0") end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/rabl_test.rb
test/rabl_test.rb
require_relative 'test_helper' begin require 'rabl' require 'ostruct' require 'json' require 'active_support/core_ext/array/extract_options' require 'active_support/core_ext/hash/conversions' class RablTest < Minitest::Test def rabl_app(&block) mock_app { set :views, __dir__ + '/views' get '/', &block } get '/' end it 'renders inline rabl strings' do rabl_app do @foo = OpenStruct.new(:baz => 'w00t') rabl %q{ object @foo attributes :baz } end assert ok? assert_equal '{"openstruct":{"baz":"w00t"}}', body end it 'renders .rabl files in views path' do rabl_app do @foo = OpenStruct.new(:bar => 'baz') rabl :hello end assert ok? assert_equal '{"openstruct":{"bar":"baz"}}', body end it "renders with file layouts" do rabl_app { @foo = OpenStruct.new(:bar => 'baz') rabl :hello, :layout => :layout2 } assert ok? assert_equal '{"qux":{"openstruct":{"bar":"baz"}}}', body end it "raises error if template not found" do mock_app { get('/') { rabl :no_such_template } } assert_raises(Errno::ENOENT) { get('/') } end it "passes rabl options to the rabl engine" do mock_app do get('/') do @foo = OpenStruct.new(:bar => 'baz') rabl %q{ object @foo attributes :bar }, :format => 'xml' end end get '/' assert ok? assert_body '<?xml version="1.0" encoding="UTF-8"?><openstruct><bar>baz</bar></openstruct>' end it "passes default rabl options to the rabl engine" do mock_app do set :rabl, :format => 'xml' get('/') do @foo = OpenStruct.new(:bar => 'baz') rabl %q{ object @foo attributes :bar } end end get '/' assert ok? assert_body '<?xml version="1.0" encoding="UTF-8"?><openstruct><bar>baz</bar></openstruct>' end end rescue LoadError warn "#{$!}: skipping rabl tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/integration_async_test.rb
test/integration_async_test.rb
require_relative 'test_helper' require File.expand_path('integration_async_helper', __dir__) # These tests are like integration_test, but they test asynchronous streaming. class IntegrationAsyncTest < Minitest::Test extend IntegrationAsyncHelper attr_accessor :server it 'streams async' do Timeout.timeout(3) do chunks = [] server.get_stream '/async' do |chunk| next if chunk.empty? chunks << chunk case chunk when "hi!" then server.get "/send?msg=hello" when "hello" then server.get "/send?close=1" end end assert_equal ['hi!', 'hello'], chunks end end it 'streams async from subclass' do Timeout.timeout(3) do chunks = [] server.get_stream '/subclass/async' do |chunk| next if chunk.empty? chunks << chunk case chunk when "hi!" then server.get "/subclass/send?msg=hello" when "hello" then server.get "/subclass/send?close=1" end end assert_equal ['hi!', 'hello'], chunks end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/route_added_hook_test.rb
test/route_added_hook_test.rb
require_relative 'test_helper' module RouteAddedTest @routes, @procs = [], [] def self.routes ; @routes ; end def self.procs ; @procs ; end def self.route_added(verb, path, proc) @routes << [verb, path] @procs << proc end end class RouteAddedHookTest < Minitest::Test setup do RouteAddedTest.routes.clear RouteAddedTest.procs.clear end it "should be notified of an added route" do mock_app(Class.new(Sinatra::Base)) do register RouteAddedTest get('/') {} end assert_equal [["GET", "/"], ["HEAD", "/"]], RouteAddedTest.routes end it "should include hooks from superclass" do a = Class.new(Class.new(Sinatra::Base)) b = Class.new(a) a.register RouteAddedTest b.class_eval { post("/sub_app_route") {} } assert_equal [["POST", "/sub_app_route"]], RouteAddedTest.routes end it "should only run once per extension" do mock_app(Class.new(Sinatra::Base)) do register RouteAddedTest register RouteAddedTest get('/') {} end assert_equal [["GET", "/"], ["HEAD", "/"]], RouteAddedTest.routes end it "should pass route blocks as an argument" do mock_app(Class.new(Sinatra::Base)) do register RouteAddedTest get('/') {} end assert_kind_of Proc, RouteAddedTest.procs.first end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/nokogiri_test.rb
test/nokogiri_test.rb
require_relative 'test_helper' begin require 'nokogiri' class NokogiriTest < Minitest::Test def nokogiri_app(&block) mock_app do set :views, __dir__ + '/views' get('/', &block) end get '/' end it 'renders inline Nokogiri strings' do nokogiri_app { nokogiri '' } assert ok? assert_body %(<?xml version="1.0"?>\n) end it 'renders inline blocks' do nokogiri_app do @name = "Frank & Mary" nokogiri { |xml| xml.couple @name } end assert ok? assert_body %(<?xml version="1.0"?>\n<couple>Frank &amp; Mary</couple>\n) end it 'renders .nokogiri files in views path' do nokogiri_app do @name = "Blue" nokogiri :hello end assert ok? assert_body "<?xml version=\"1.0\"?>\n<exclaim>You're my boy, Blue!</exclaim>\n" end it "renders with inline layouts" do next if Tilt::VERSION <= "1.1" mock_app do layout { %(xml.layout { xml << yield }) } get('/') { nokogiri %(xml.em 'Hello World') } end get '/' assert ok? assert_body %(<?xml version="1.0"?>\n<layout>\n <em>Hello World</em>\n</layout>\n) end it "renders with file layouts" do next if Tilt::VERSION <= "1.1" nokogiri_app { nokogiri %(xml.em 'Hello World'), :layout => :layout2 } assert ok? assert_body %(<?xml version="1.0"?>\n<layout>\n <em>Hello World</em>\n</layout>\n) end it "raises error if template not found" do mock_app { get('/') { nokogiri :no_such_template } } assert_raises(Errno::ENOENT) { get('/') } end end rescue LoadError warn "#{$!}: skipping nokogiri tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/integration_helper.rb
test/integration_helper.rb
require 'sinatra/base' require 'rbconfig' require 'open-uri' require 'sinatra/runner' module IntegrationHelper class BaseServer < Sinatra::Runner extend Enumerable attr_accessor :server, :port alias name server def self.all @all ||= [] end def self.all_async @all_async ||= [] end def self.each(&block) all.each(&block) end def self.run(server, port, async: false) new(server, port, async).run end def app_file File.expand_path('integration/app.rb', __dir__) end def environment "development" end def initialize(server, port, async) @installed, @pipe, @server, @port = nil, nil, server, port ENV['PUMA_MIN_THREADS'] = '1' if server == 'puma' if async Server.all_async << self else Server.all << self end end def run return unless installed? kill @log = +"" super at_exit { kill } end def installed? return @installed unless @installed.nil? s = server == 'HTTP' ? 'net/http/server' : server require s @installed = true rescue LoadError warn "#{server} is not installed, skipping integration tests" @installed = false end def command @command ||= begin cmd = ["APP_ENV=#{environment}", "exec"] if RbConfig.respond_to? :ruby cmd << RbConfig.ruby.inspect else file, dir = RbConfig::CONFIG.values_at('ruby_install_name', 'bindir') cmd << File.expand_path(file, dir).inspect end cmd << "-w" unless net_http_server? cmd << "-I" << File.expand_path('../lib', __dir__).inspect cmd << app_file.inspect << '-s' << server << '-o' << '127.0.0.1' << '-p' << port cmd << "-e" << environment.to_s << '2>&1' cmd.join " " end end def webrick? name.to_s == "webrick" end def puma? name.to_s == "puma" end def falcon? name.to_s == "falcon" end def trinidad? name.to_s == "trinidad" end def net_http_server? name.to_s == 'HTTP' end def warnings log.scan(%r[(?:\(eval|lib/sinatra).*warning:.*$]) end def run_test(target, &block) retries ||= 3 target.server = self run unless alive? target.instance_eval(&block) rescue Exception => error retries -= 1 kill retries < 0 ? retry : raise(error) end end Server = BaseServer def it(message, &block) Server.each do |server| next unless server.installed? super("with #{server.name}: #{message}") { server.run_test(self, &block) } end end def self.extend_object(obj) super base_port = 5000 + Process.pid % 100 servers = Sinatra::Base.server.dup # TruffleRuby doesn't support `Fiber.set_scheduler` yet unsupported_truffleruby = RUBY_ENGINE == "truffleruby" && !Fiber.respond_to?(:set_scheduler) # Ruby 2.7 uses falcon 0.42.3 which isn't working with rackup 2.2.0+ too_old_ruby = RUBY_VERSION <= "3.0.0" if unsupported_truffleruby || too_old_ruby warn "skip falcon server" servers.delete('falcon') end servers.each_with_index do |server, index| Server.run(server, base_port+index) end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/middleware_test.rb
test/middleware_test.rb
require_relative 'test_helper' class MiddlewareTest < Minitest::Test setup do @app = mock_app(Sinatra::Application) do get('/*')do response.headers['X-Tests'] = env['test.ran']. map { |n| n.split('::').last }. join(', ') env['PATH_INFO'] end end end class MockMiddleware < Struct.new(:app) def call(env) (env['test.ran'] ||= []) << self.class.to_s app.call(env) end end class UpcaseMiddleware < MockMiddleware def call(env) env['PATH_INFO'] = env['PATH_INFO'].upcase super end end it "is added with Sinatra::Application.use" do @app.use UpcaseMiddleware get '/hello-world' assert ok? assert_equal '/HELLO-WORLD', body end class DowncaseMiddleware < MockMiddleware def call(env) env['PATH_INFO'] = env['PATH_INFO'].downcase super end end it "runs in the order defined" do @app.use UpcaseMiddleware @app.use DowncaseMiddleware get '/Foo' assert_equal "/foo", body assert_equal "UpcaseMiddleware, DowncaseMiddleware", response['X-Tests'] end it "resets the prebuilt pipeline when new middleware is added" do @app.use UpcaseMiddleware get '/Foo' assert_equal "/FOO", body @app.use DowncaseMiddleware get '/Foo' assert_equal '/foo', body assert_equal "UpcaseMiddleware, DowncaseMiddleware", response['X-Tests'] end it "works when app is used as middleware" do @app.use UpcaseMiddleware @app = @app.new get '/Foo' assert_equal "/FOO", body assert_equal "UpcaseMiddleware", response['X-Tests'] end class FreezeMiddleware < MockMiddleware def call(env) req = Rack::Request.new(env) req.update_param('bar', 'baz'.freeze) super end end it "works when middleware adds a frozen param" do @app.use FreezeMiddleware get '/Foo' end class SpecialConstsMiddleware < MockMiddleware def call(env) req = Rack::Request.new(env) req.update_param('s', :s) req.update_param('i', 1) req.update_param('c', 3.to_c) req.update_param('t', true) req.update_param('f', false) req.update_param('n', nil) super end end it "handles params when the params contains true/false values" do @app.use SpecialConstsMiddleware get '/' end class KeywordArgumentInitializationMiddleware < MockMiddleware def initialize(app, **) super app end end it "handles keyword arguments" do @app.use KeywordArgumentInitializationMiddleware, argument: "argument" get '/' end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/encoding_test.rb
test/encoding_test.rb
require_relative 'test_helper' require 'erb' class BaseTest < Minitest::Test setup do @base = Sinatra.new(Sinatra::Base) @base.set :views, __dir__ + "/views" end it 'allows unicode strings in ascii templates per default (1.9)' do next unless defined? Encoding @base.new!.erb(File.read(@base.views + "/ascii.erb").encode("ASCII"), {}, :value => "åkej") end it 'allows ascii strings in unicode templates per default (1.9)' do next unless defined? Encoding @base.new!.erb(:utf8, {}, :value => "Some Lyrics".encode("ASCII")) end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/contest.rb
test/contest.rb
# Copyright (c) 2009 Damian Janowski and Michel Martens for Citrusbyte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require "rubygems" require "minitest/autorun" # Contest adds +teardown+, +test+ and +context+ as class methods, and the # instance methods +setup+ and +teardown+ now iterate on the corresponding # blocks. Note that all setup and teardown blocks must be defined with the # block syntax. Adding setup or teardown instance methods defeats the purpose # of this library. class Minitest::Test def self.setup(&block) setup_blocks << block end def self.teardown(&block) teardown_blocks << block end def self.setup_blocks() @setup_blocks ||= [] end def self.teardown_blocks() @teardown_blocks ||= [] end def setup_blocks(base = self.class) setup_blocks base.superclass if base.superclass.respond_to? :setup_blocks base.setup_blocks.each do |block| instance_eval(&block) end end def teardown_blocks(base = self.class) teardown_blocks base.superclass if base.superclass.respond_to? :teardown_blocks base.teardown_blocks.each do |block| instance_eval(&block) end end alias setup setup_blocks alias teardown teardown_blocks def self.context(*name, &block) subclass = Class.new(self) remove_tests(subclass) subclass.class_eval(&block) if block_given? const_set(context_name(name.join(" ")), subclass) end def self.test(name, &block) define_method(test_name(name), &block) end class << self alias_method :should, :test alias_method :describe, :context end private def self.context_name(name) # "Test#{sanitize_name(name).gsub(/(^| )(\w)/) { $2.upcase }}".to_sym name = "Test#{sanitize_name(name).gsub(/(^| )(\w)/) { $2.upcase }}" name.tr(" ", "_").to_sym end def self.test_name(name) name = "test_#{sanitize_name(name).gsub(/\s+/,'_')}_0" name = name.succ while method_defined? name name.to_sym end def self.sanitize_name(name) # name.gsub(/\W+/, ' ').strip name.gsub(/\W+/, ' ') end def self.remove_tests(subclass) subclass.public_instance_methods.grep(/^test_/).each do |meth| subclass.send(:undef_method, meth.to_sym) end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/templates_test.rb
test/templates_test.rb
require_relative 'test_helper' File.delete(__dir__ + '/views/layout.test') rescue nil class TestTemplate < Tilt::Template def prepare end def evaluate(scope, locals={}, &block) inner = block ? block.call : '' data + inner end Tilt.register 'test', self end class TemplatesTest < Minitest::Test def render_app(base=Sinatra::Base, options = {}, &block) base, options = Sinatra::Base, base if base.is_a? Hash mock_app(base) do set :views, __dir__ + '/views' set options get('/', &block) template(:layout3) { "Layout 3!\n" } end get '/' end def with_default_layout layout = __dir__ + '/views/layout.test' File.open(layout, 'wb') { |io| io.write "Layout!\n" } yield ensure File.unlink(layout) rescue nil end it 'falls back to engine layout' do mock_app do template(:layout3) { 'Layout 3!<%= yield %>' } set :erb, :layout => :layout3 get('/') do erb('Hello World!', { :layout => true }) end end get '/' assert ok? assert_equal "Layout 3!Hello World!", body end it 'falls back to default layout if engine layout is true' do mock_app do template(:layout) { 'Layout!!! <%= yield %>' } set :erb, :layout => true get('/') do erb('Hello World!', { :layout => true }) end end get '/' assert ok? assert_equal "Layout!!! Hello World!", body end it 'renders no layout if layout if falsy' do mock_app do template(:layout) { 'Layout!!! <%= yield %>' } set :erb, :layout => true get('/') do erb('Hello World!', { :layout => nil }) end end get '/' assert ok? assert_equal "Hello World!", body end it 'allows overriding false default layout with explicit true' do mock_app do template(:layout) { 'Layout!!! <%= yield %>' } set :erb, :layout => false get('/') do erb('Hello World!', { :layout => true }) end end get '/' assert ok? assert_equal "Layout!!! Hello World!", body end it 'renders String templates directly' do render_app { render(:test, 'Hello World') } assert ok? assert_equal 'Hello World', body end it 'allows to specify path/line when rendering with String' do path = 'example.txt' line = 228 begin render_app { render :erb, '<%= doesnotexist %>', {:path => path, :line => line} } rescue NameError => e assert_match(/#{path}:#{line}/, e.backtrace.first) end end it 'allows to specify path/line when rendering with Proc' do path = 'example.txt' line = 900 begin render_app { render :erb, Proc.new { '<%= doesnotexist %>' }, {:path => path, :line => line} } rescue NameError => e assert_match(/#{path}:#{line}/, e.backtrace.first) end end it 'renders Proc templates using the call result' do render_app { render(:test, Proc.new {'Hello World'}) } assert ok? assert_equal 'Hello World', body end it 'looks up Symbol templates in views directory' do render_app { render(:test, :hello) } assert ok? assert_equal "Hello World!\n", body end it 'uses the default layout template if not explicitly overridden' do with_default_layout do render_app { render(:test, :hello) } assert ok? assert_equal "Layout!\nHello World!\n", body end end it 'uses the default layout template if not really overridden' do with_default_layout do render_app { render(:test, :hello, :layout => true) } assert ok? assert_equal "Layout!\nHello World!\n", body end end it 'uses the layout template specified' do render_app { render(:test, :hello, :layout => :layout2) } assert ok? assert_equal "Layout 2!\nHello World!\n", body end it 'uses layout templates defined with the #template method' do render_app { render(:test, :hello, :layout => :layout3) } assert ok? assert_equal "Layout 3!\nHello World!\n", body end it 'avoids wrapping layouts around nested templates' do render_app { render(:str, :nested, :layout => :layout2) } assert ok? assert_equal( "<h1>String Layout!</h1>\n<content><h1>Hello From String</h1></content>", body ) end it 'allows explicitly wrapping layouts around nested templates' do render_app { render(:str, :explicitly_nested, :layout => :layout2) } assert ok? assert_equal( "<h1>String Layout!</h1>\n<content><h1>String Layout!</h1>\n<h1>Hello From String</h1></content>", body ) end it 'two independent render calls do not disable layouts' do render_app do render :str, :explicitly_nested, :layout => :layout2 render :str, :nested, :layout => :layout2 end assert ok? assert_equal( "<h1>String Layout!</h1>\n<content><h1>Hello From String</h1></content>", body ) end it 'is possible to use partials in layouts' do render_app do settings.layout { "<%= erb 'foo' %><%= yield %>" } erb 'bar' end assert ok? assert_equal "foobar", body end it 'loads templates from source file' do mock_app { enable(:inline_templates) } assert_equal "this is foo\n\n", @app.templates[:foo][0] assert_equal "X\n= yield\nX\n", @app.templates[:layout][0] end it 'ignores spaces after names of inline templates' do mock_app { enable(:inline_templates) } assert_equal "There's a space after 'bar'!\n\n", @app.templates[:bar][0] assert_equal "this is not foo\n\n", @app.templates[:"foo bar"][0] end it 'loads templates from given source file' do mock_app { set(:inline_templates, __FILE__) } assert_equal "this is foo\n\n", @app.templates[:foo][0] end test 'inline_templates ignores IO errors' do mock_app { set(:inline_templates, '/foo/bar') } assert @app.templates.empty? end it 'allows unicode in inline templates' do mock_app { set(:inline_templates, __FILE__) } assert_equal( "Den som tror at hemma det är där man bor har aldrig vart hos mig.\n\n", @app.templates[:umlaut][0] ) end it 'loads templates from specified views directory' do render_app { render(:test, :hello, :views => settings.views + '/foo') } assert_equal "from another views directory\n", body end it 'takes views directory into consideration for caching' do render_app do render(:test, :hello) + render(:test, :hello, :views => settings.views + '/foo') end assert_equal "Hello World!\nfrom another views directory\n", body end it 'passes locals to the layout' do mock_app do template(:my_layout) { 'Hello <%= name %>!<%= yield %>' } get('/') do erb('<p><%= name %> content</p>', { :layout => :my_layout }, { :name => 'Mike'}) end end get '/' assert ok? assert_equal 'Hello Mike!<p>Mike content</p>', body end it 'sets layout-only options via layout_options' do render_app do render(:str, :in_a, :views => settings.views + '/a', :layout_options => { :views => settings.views }, :layout => :layout2) end assert ok? assert_equal "<h1>String Layout!</h1>\nGimme an A!\n", body end it 'loads templates defined in subclasses' do base = Class.new(Sinatra::Base) base.template(:foo) { 'bar' } render_app(base) { render(:test, :foo) } assert ok? assert_equal 'bar', body end it 'allows setting default content type' do render_app(:str => { :default_content_type => :txt }) { render :str, 'foo' } assert_equal 'text/plain;charset=utf-8', response['Content-Type'] end it 'allows setting default content type per template engine' do render_app(:str => { :content_type => :txt }) { render :str, 'foo' } assert_equal 'text/plain;charset=utf-8', response['Content-Type'] end it 'setting default content type does not affect other template engines' do render_app(:str => { :content_type => :txt }) { render :test, 'foo' } assert_equal 'text/html;charset=utf-8', response['Content-Type'] end it 'setting default content type per template engine does not override content_type' do render_app :str => { :content_type => :txt } do content_type :html render :str, 'foo' end assert_equal 'text/html;charset=utf-8', response['Content-Type'] end it 'uses templates in superclasses before subclasses' do base = Class.new(Sinatra::Base) base.template(:foo) { 'template in superclass' } assert_equal 'template in superclass', base.templates[:foo].first.call mock_app(base) do set :views, __dir__ + '/views' template(:foo) { 'template in subclass' } get('/') { render :test, :foo } end assert_equal 'template in subclass', @app.templates[:foo].first.call get '/' assert ok? assert_equal 'template in subclass', body end it "is possible to use a different engine for the layout than for the template itself explicitly" do render_app do settings.template(:layout) { 'Hello <%= yield %>!' } render :str, "<%= 'World' %>", :layout_engine => :erb end assert_equal "Hello <%= 'World' %>!", body end it "is possible to use a different engine for the layout than for the template itself globally" do render_app :str => { :layout_engine => :erb } do settings.template(:layout) { 'Hello <%= yield %>!' } render :str, "<%= 'World' %>" end assert_equal "Hello <%= 'World' %>!", body end it "does not leak the content type to the template" do render_app :str => { :layout_engine => :erb } do settings.template(:layout) { 'Hello <%= yield %>!' } render :str, "<%= 'World' %>", :content_type => :txt end assert_equal "text/html;charset=utf-8", headers['Content-Type'] end it "is possible to register another template" do Tilt.register "html.erb", Tilt[:erb] render_app { render :erb, :calc } assert_equal '2', body end it "passes scope to the template" do mock_app do template(:scoped) { 'Hello <%= foo %>' } get('/') do some_scope = Object.new def some_scope.foo() 'World!' end erb :scoped, :scope => some_scope end end get '/' assert ok? assert_equal 'Hello World!', body end it "is possible to use custom logic for finding template files" do mock_app do set :views, ["a", "b"].map { |d| __dir__ + '/views/' + d } def find_template(views, name, engine, &block) Array(views).each { |v| super(v, name, engine, &block) } end get('/:name') { render(:str, params[:name].to_sym) } end get '/in_a' assert_body 'Gimme an A!' get '/in_b' assert_body 'Gimme a B!' end end # __END__ : this is not the real end of the script. __END__ @@ foo this is foo @@ bar There's a space after 'bar'! @@ foo bar this is not foo @@ umlaut Den som tror at hemma det är där man bor har aldrig vart hos mig. @@ layout X = yield X
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/server_test.rb
test/server_test.rb
require_relative 'test_helper' require 'stringio' module Rackup::Handler class Mock extend Minitest::Assertions # Allow assertions in request context def self.assertions @assertions ||= 0 end def self.assertions= assertions @assertions = assertions end def self.run(app, options={}) assert(app < Sinatra::Base) assert_equal 9001, options[:Port] assert_equal 'foo.local', options[:Host] yield new end def stop end end register :mock, Mock end class ServerTest < Minitest::Test setup do mock_app do set :server, 'mock' set :bind, 'foo.local' set :port, 9001 end $stderr = StringIO.new end def teardown $stderr = STDERR end it "locates the appropriate Rack handler and calls ::run" do @app.run! end context "event hooks" do dummy_class = Class.new do def self.start_hook; end def self.stop_hook; end end it "runs the provided code when the server starts" do @app.on_start do dummy_class.start_hook end mock = Minitest::Mock.new mock.expect(:call, nil) dummy_class.stub(:start_hook, mock) do @app.run! end assert_mock mock end it "runs the provided code when the server stops" do @app.on_stop do dummy_class.stop_hook end mock = Minitest::Mock.new mock.expect(:call, nil) dummy_class.stub(:stop_hook, mock) do @app.run! @app.quit! end assert_mock mock end end it "sets options on the app before running" do @app.run! :sessions => true assert @app.sessions? end it "falls back on the next server handler when not found" do @app.run! :server => %w[foo bar mock] end it "initializes Rack middleware immediately on server run" do class MyMiddleware @@initialized = false def initialize(app) @@initialized = true end def self.initialized @@initialized end def call(env) end end @app.use MyMiddleware assert_equal(MyMiddleware.initialized, false) @app.run! assert_equal(MyMiddleware.initialized, true) end describe "Quiet mode" do it "sends data to stderr when server starts and stops" do @app.run! assert_match(/\=\= Sinatra/, $stderr.string) end context "when quiet mode is activated" do it "does not generate Sinatra start and stop messages" do @app.run! quiet: true refute_match(/\=\= Sinatra/, $stderr.string) end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/filter_test.rb
test/filter_test.rb
require_relative 'test_helper' class BeforeFilterTest < Minitest::Test it "executes filters in the order defined" do count = 0 mock_app do get('/') { 'Hello World' } before do assert_equal 0, count count = 1 end before do assert_equal 1, count count = 2 end end get '/' assert ok? assert_equal 2, count assert_equal 'Hello World', body end it "can modify the request" do mock_app do get('/foo') { 'foo' } get('/bar') { 'bar' } before { request.path_info = '/bar' } end get '/foo' assert ok? assert_equal 'bar', body end it "can modify instance variables available to routes" do mock_app do before { @foo = 'bar' } get('/foo') { @foo } end get '/foo' assert ok? assert_equal 'bar', body end it "allows redirects" do mock_app do before { redirect '/bar' } get('/foo') do fail 'before block should have halted processing' 'ORLY?!' end end get '/foo' assert redirect? assert_equal 'http://example.org/bar', response['Location'] assert_equal '', body end it "does not modify the response with its return value" do mock_app do before { 'Hello World!' } get('/foo') do assert_equal [], response.body 'cool' end end get '/foo' assert ok? assert_equal 'cool', body end it "does modify the response with halt" do mock_app do before { halt 302, 'Hi' } get '/foo' do "should not happen" end end get '/foo' assert_equal 302, response.status assert_equal 'Hi', body end it "gives you access to params" do mock_app do before { @foo = params['foo'] } get('/foo') { @foo } end get '/foo?foo=cool' assert ok? assert_equal 'cool', body end it "properly unescapes parameters" do mock_app do before { @foo = params['foo'] } get('/foo') { @foo } end get '/foo?foo=bar%3Abaz%2Fbend' assert ok? assert_equal 'bar:baz/bend', body end it "runs filters defined in superclasses" do base = Class.new(Sinatra::Base) base.before { @foo = 'hello from superclass' } mock_app(base) { get('/foo') { @foo } } get '/foo' assert_equal 'hello from superclass', body end it 'does not run before filter when serving static files' do ran_filter = false mock_app do before { ran_filter = true } set :static, true set :public_folder, __dir__ end get "/#{File.basename(__FILE__)}" assert ok? assert_equal File.read(__FILE__), body assert !ran_filter end it 'takes an optional route pattern' do ran_filter = false mock_app do before("/b*") { ran_filter = true } get('/foo') { } get('/bar') { } end get '/foo' assert !ran_filter get '/bar' assert ran_filter end it 'generates block arguments from route pattern' do subpath = nil mock_app do before("/foo/:sub") { |s| subpath = s } get('/foo/*') { } end get '/foo/bar' assert_equal subpath, 'bar' end it 'can catch exceptions in before filters and handle them properly' do doodle = '' mock_app do before do doodle += 'This begins' raise StandardError, "before" end get "/" do doodle = 'and runs' end error 500 do "Error handled #{env['sinatra.error'].message}" end end doodle = '' get '/' assert_equal 'Error handled before', body assert_equal 'This begins', doodle end end class AfterFilterTest < Minitest::Test it "executes before and after filters in correct order" do invoked = 0 mock_app do before { invoked = 2 } get('/') { invoked += 2; 'hello' } after { invoked *= 2 } end get '/' assert ok? assert_equal 8, invoked end it "executes filters in the order defined" do count = 0 mock_app do get('/') { 'Hello World' } after do assert_equal 0, count count = 1 end after do assert_equal 1, count count = 2 end end get '/' assert ok? assert_equal 2, count assert_equal 'Hello World', body end it "allows redirects" do mock_app do get('/foo') { 'ORLY' } after { redirect '/bar' } end get '/foo' assert redirect? assert_equal 'http://example.org/bar', response['Location'] assert_equal '', body end it "does not modify the response with its return value" do mock_app do get('/foo') { 'cool' } after { 'Hello World!' } end get '/foo' assert ok? assert_equal 'cool', body end it "does modify the response with halt" do mock_app do get '/foo' do "should not be returned" end after { halt 302, 'Hi' } end get '/foo' assert_equal 302, response.status assert_equal 'Hi', body end it "runs filters defined in superclasses" do count = 2 base = Class.new(Sinatra::Base) base.after { count *= 2 } mock_app(base) do get('/foo') do count += 2 "ok" end end get '/foo' assert_equal 8, count end it "respects content type set in superclass filter" do base = Class.new(Sinatra::Base) base.before { content_type :json } mock_app(base) do get('/foo'){ {foo: :bar}.to_json } end get '/foo' assert_equal 'application/json', response.headers['Content-Type'] end it 'does not run after filter when serving static files' do ran_filter = false mock_app do after { ran_filter = true } set :static, true set :public_folder, __dir__ end get "/#{File.basename(__FILE__)}" assert ok? assert_equal File.read(__FILE__), body assert !ran_filter end it 'takes an optional route pattern' do ran_filter = false mock_app do after("/b*") { ran_filter = true } get('/foo') { } get('/bar') { } end get '/foo' assert !ran_filter get '/bar' assert ran_filter end it 'changes to path_info from a pattern matching before filter are respected when routing' do mock_app do before('/foo') { request.path_info = '/bar' } get('/bar') { 'blah' } end get '/foo' assert ok? assert_equal 'blah', body end it 'generates block arguments from route pattern' do subpath = nil mock_app do after("/foo/:sub") { |s| subpath = s } get('/foo/*') { } end get '/foo/bar' assert_equal subpath, 'bar' end it 'is possible to access url params from the route param' do ran = false mock_app do get('/foo/*') { } before('/foo/:sub') do assert_equal params[:sub], 'bar' ran = true end end get '/foo/bar' assert ran end it 'is possible to apply host_name conditions to before filters with no path' do ran = false mock_app do before(:host_name => 'example.com') { ran = true } get('/') { 'welcome' } end get('/', {}, { 'HTTP_HOST' => 'example.org' }) assert !ran get('/', {}, { 'HTTP_HOST' => 'example.com' }) assert ran end it 'is possible to apply host_name conditions to before filters with a path' do ran = false mock_app do before('/foo', :host_name => 'example.com') { ran = true } get('/') { 'welcome' } end get('/', {}, { 'HTTP_HOST' => 'example.com' }) assert !ran get('/foo', {}, { 'HTTP_HOST' => 'example.org' }) assert !ran get('/foo', {}, { 'HTTP_HOST' => 'example.com' }) assert ran end it 'is possible to apply host_name conditions to after filters with no path' do ran = false mock_app do after(:host_name => 'example.com') { ran = true } get('/') { 'welcome' } end get('/', {}, { 'HTTP_HOST' => 'example.org' }) assert !ran get('/', {}, { 'HTTP_HOST' => 'example.com' }) assert ran end it 'is possible to apply host_name conditions to after filters with a path' do ran = false mock_app do after('/foo', :host_name => 'example.com') { ran = true } get('/') { 'welcome' } end get('/', {}, { 'HTTP_HOST' => 'example.com' }) assert !ran get('/foo', {}, { 'HTTP_HOST' => 'example.org' }) assert !ran get('/foo', {}, { 'HTTP_HOST' => 'example.com' }) assert ran end it 'is possible to apply user_agent conditions to before filters with no path' do ran = false mock_app do before(:user_agent => /foo/) { ran = true } get('/') { 'welcome' } end get('/', {}, { 'HTTP_USER_AGENT' => 'bar' }) assert !ran get('/', {}, { 'HTTP_USER_AGENT' => 'foo' }) assert ran end it 'is possible to apply user_agent conditions to before filters with a path' do ran = false mock_app do before('/foo', :user_agent => /foo/) { ran = true } get('/') { 'welcome' } end get('/', {}, { 'HTTP_USER_AGENT' => 'foo' }) assert !ran get('/foo', {}, { 'HTTP_USER_AGENT' => 'bar' }) assert !ran get('/foo', {}, { 'HTTP_USER_AGENT' => 'foo' }) assert ran end it 'can add params' do mock_app do before { params['foo'] = 'bar' } get('/') { params['foo'] } end get '/' assert_body 'bar' end it 'can add params on a single path' do mock_app do before('/hi'){ params['foo'] = 'bar' } get('/hi') { params['foo'] } end get '/hi' assert_body 'bar' end # ref: issue #1567 it 'can add params on named parameters path' do mock_app do before('/:id/hi'){ params['foo'] = 'bar' } get('/:id/hi') { params['foo'] } end get '/:id/hi' assert_body 'bar' end it 'can remove params' do mock_app do before { params.delete('foo') } get('/') { params['foo'].to_s } end get '/?foo=bar' assert_body '' end it 'is possible to apply user_agent conditions to after filters with no path' do ran = false mock_app do after(:user_agent => /foo/) { ran = true } get('/') { 'welcome' } end get('/', {}, { 'HTTP_USER_AGENT' => 'bar' }) assert !ran get('/', {}, { 'HTTP_USER_AGENT' => 'foo' }) assert ran end it 'is possible to apply user_agent conditions to after filters with a path' do ran = false mock_app do after('/foo', :user_agent => /foo/) { ran = true } get('/') { 'welcome' } end get('/', {}, { 'HTTP_USER_AGENT' => 'foo' }) assert !ran get('/foo', {}, { 'HTTP_USER_AGENT' => 'bar' }) assert !ran get('/foo', {}, { 'HTTP_USER_AGENT' => 'foo' }) assert ran end it 'only triggers provides condition if conforms with current Content-Type' do mock_app do before(:provides => :txt) { @type = 'txt' } before(:provides => :html) { @type = 'html' } get('/') { @type } end get('/', {}, { 'HTTP_ACCEPT' => '*/*' }) assert_body 'txt' end it 'can catch exceptions in after filters and handle them properly' do doodle = '' mock_app do after do doodle += ' and after' raise StandardError, "after" end get "/foo" do doodle = 'Been now' raise StandardError, "now" end get "/" do doodle = 'Been now' end error 500 do "Error handled #{env['sinatra.error'].message}" end end get '/foo' assert_equal 'Error handled now', body assert_equal 'Been now and after', doodle doodle = '' get '/' assert_equal 'Error handled after', body assert_equal 'Been now and after', doodle end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/streaming_test.rb
test/streaming_test.rb
require_relative 'test_helper' class StreamingTest < Minitest::Test Stream = Sinatra::Helpers::Stream it 'returns the concatenated body' do mock_app do get('/') do stream do |out| out << "Hello" << " " out << "World!" end end end get('/') assert_body "Hello World!" end it 'always yields strings' do stream = Stream.new { |out| out << :foo } stream.each { |str| assert_equal 'foo', str } end it 'postpones body generation' do step = 0 stream = Stream.new do |out| 10.times do out << step step += 1 end end stream.each do |s| assert_equal s, step.to_s step += 1 end end it 'calls the callback after it is done' do step = 0 final = 0 stream = Stream.new { |_| 10.times { step += 1 }} stream.callback { final = step } stream.each {|_|} assert_equal 10, final end it 'does not trigger the callback if close is set to :keep_open' do step = 0 final = 0 stream = Stream.new(Stream, :keep_open) { |_| 10.times { step += 1 } } stream.callback { final = step } stream.each {|_|} assert_equal 0, final end it 'allows adding more than one callback' do a = b = false stream = Stream.new { } stream.callback { a = true } stream.callback { b = true } stream.each {|_| } assert a, 'should trigger first callback' assert b, 'should trigger second callback' end class MockScheduler def initialize(*) @schedule, @defer = [], [] end def schedule(&block) @schedule << block end def defer(&block) @defer << block end def schedule!(*) @schedule.pop.call until @schedule.empty? end def defer!(*) @defer.pop.call until @defer.empty? end end it 'allows dropping in another scheduler' do scheduler = MockScheduler.new processing = sending = done = false stream = Stream.new(scheduler) do |out| processing = true out << :foo end stream.each { sending = true} stream.callback { done = true } scheduler.schedule! assert !processing assert !sending assert !done scheduler.defer! assert processing assert !sending assert !done scheduler.schedule! assert sending assert done end it 'schedules exceptions to be raised on the main thread/event loop/...' do scheduler = MockScheduler.new Stream.new(scheduler) { fail 'should be caught' }.each { } scheduler.defer! assert_raises(RuntimeError) { scheduler.schedule! } end it 'does not trigger an infinite loop if you call close in a callback' do stream = Stream.new { |out| out.callback { out.close }} stream.each { |_| } end it 'gives access to route specific params' do mock_app do get('/:name') do stream { |o| o << params[:name] } end end get '/foo' assert_body 'foo' end it 'sets up async.close if available' do ran = false mock_app do get('/') do close = Object.new def close.callback; yield end def close.errback; end env['async.close'] = close stream(:keep_open) do |out| out.callback { ran = true } out.close end end end get '/' assert ran end it 'has a public interface to inspect its open/closed state' do stream = Stream.new(Stream) { |out| out << :foo } assert !stream.closed? stream.close assert stream.closed? end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/routing_test.rb
test/routing_test.rb
require_relative 'test_helper' # Helper method for easy route pattern matching testing def route_def(pattern) mock_app { get(pattern) { } } end class PatternLookAlike def to_pattern(*) self end def params(input) { "one" => +"this", "two" => +"is", "three" => +"a", "four" => +"test" } end end class RoutingTest < Minitest::Test %w[get put post delete options patch link unlink].each do |verb| it "defines #{verb.upcase} request handlers with #{verb}" do mock_app { send verb, '/hello' do 'Hello World' end } request = Rack::MockRequest.new(@app) response = request.request(verb.upcase, '/hello', {}) assert response.ok? assert_equal 'Hello World', response.body end end it "defines HEAD request handlers with HEAD" do mock_app { head '/hello' do response['X-Hello'] = 'World!' 'remove me' end } request = Rack::MockRequest.new(@app) response = request.request('HEAD', '/hello', {}) assert response.ok? assert_equal 'World!', response['X-Hello'] assert_equal '', response.body end it "400s when request params contain conflicting types" do mock_app { get('/foo') { } } request = Rack::MockRequest.new(@app) response = request.request('GET', '/foo?bar=&bar[]=', {}) assert response.bad_request? end it "404s when no route satisfies the request" do mock_app { get('/foo') { } } get '/bar' assert_equal 404, status end it "404s and sets X-Cascade header when no route satisfies the request" do mock_app { get('/foo') { } } get '/bar' assert_equal 404, status assert_equal 'pass', response.headers['X-Cascade'] end it "404s and does not set X-Cascade header when no route satisfies the request and x_cascade has been disabled" do mock_app { disable :x_cascade get('/foo') { } } get '/bar' assert_equal 404, status assert_nil response.headers['X-Cascade'] end it "allows using unicode" do mock_app do get('/föö') { } end get '/f%C3%B6%C3%B6' assert_equal 200, status end it "it handles encoded slashes correctly" do mock_app { set :protection, :except => :path_traversal get("/:a") { |a| a } } get '/foo%2Fbar' assert_equal 200, status assert_body "foo/bar" end it "it handles encoded colons correctly" do mock_app { get("/\\:") { 'a' } get("/a/\\:") { 'b' } get("/a/\\:/b") { 'c' } get("/a/b\\:") { 'd' } get("/a/b\\: ") { 'e' } } get '/:' assert_equal 200, status assert_body "a" get '/%3a' assert_equal 200, status assert_body "a" get '/a/:' assert_equal 200, status assert_body "b" get '/a/%3a' assert_equal 200, status assert_body "b" get '/a/:/b' assert_equal 200, status assert_body "c" get '/a/%3A/b' assert_equal 200, status assert_body "c" get '/a/b:' assert_equal 200, status assert_body "d" get '/a/b%3a' assert_equal 200, status assert_body "d" get '/a/b%3a%20' assert_equal 200, status assert_body "e" get '/a/b%3a+' assert_equal 200, status assert_body "e" end it "overrides the content-type in error handlers" do mock_app { before { content_type 'text/plain' } error Sinatra::NotFound do content_type "text/html" "<h1>Not Found</h1>" end } get '/foo' assert_equal 404, status assert_equal 'text/html;charset=utf-8', response["Content-Type"] assert_equal "<h1>Not Found</h1>", response.body end it "recalculates body length correctly for 404 response" do mock_app { get '/' do @response["Content-Length"] = "30" raise Sinatra::NotFound end } get "/" assert_equal "18", response["Content-Length"] assert_equal 404, status end it "captures the exception message of a raised NotFound" do mock_app { get '/' do raise Sinatra::NotFound, "This is not a drill" end } get "/" assert_equal "19", response["Content-Length"] assert_equal 404, status assert_equal "This is not a drill", response.body end it "captures the exception message of a raised BadRequest" do mock_app { get '/' do raise Sinatra::BadRequest, "This is not a drill either" end } get "/" assert_equal "26", response["Content-Length"] assert_equal 400, status assert_equal "This is not a drill either", response.body end it "captures the custom exception message of a BadRequest" do mock_app { get('/') {} error Sinatra::BadRequest do 'This is not a drill either' end } get "/", "foo" => "", "foo[]" => "" assert_equal "26", response["Content-Length"] assert_equal 400, status assert_equal "This is not a drill either", response.body end it "returns empty when unmatched with any regex captures" do mock_app do before do # noop end get '/hello' do params.to_s end end assert get('/hello').ok? assert_body '{}' end it "uses 404 error handler for not matching route" do mock_app { not_found do "nf" end error 404 do "e" end } get "/" assert_equal "e", body assert_equal 404, status end it 'matches empty PATH_INFO to "/" if no route is defined for ""' do mock_app do get '/' do 'worked' end end get '/', {}, "PATH_INFO" => "" assert ok? assert_equal 'worked', body rescue Rack::Lint::LintError => error # Temporary fix for https://github.com/sinatra/sinatra/issues/2113 skip error.message end it 'matches empty PATH_INFO to "" if a route is defined for ""' do mock_app do disable :protection get '/' do 'did not work' end get '' do 'worked' end end get '/', {}, "PATH_INFO" => "" assert ok? assert_equal 'worked', body rescue Rack::Lint::LintError => error # Temporary fix for https://github.com/sinatra/sinatra/issues/2113 skip error.message end it 'takes multiple definitions of a route' do mock_app { user_agent(/Foo/) get '/foo' do 'foo' end get '/foo' do 'not foo' end } get '/foo', {}, 'HTTP_USER_AGENT' => 'Foo' assert ok? assert_equal 'foo', body get '/foo' assert ok? assert_equal 'not foo', body end it "exposes params with indifferent hash" do mock_app { get '/:foo' do assert_equal 'bar', params['foo'] assert params.has_key?('foo') assert_equal 'bar', params[:foo] assert params.has_key?(:foo) 'well, alright' end } get '/bar' assert_equal 'well, alright', body end it "handles params without a value" do mock_app { get '/' do assert_nil params.fetch('foo') "Given: #{params.keys.sort.join(',')}" end } get '/?foo' assert_equal 'Given: foo', body end it "merges named params and query string params in params" do mock_app { get '/:foo' do assert_equal 'bar', params['foo'] assert_equal 'biz', params['baz'] end } get '/bar?baz=biz' assert ok? end it "supports named params like /hello/:person" do mock_app { get '/hello/:person' do "Hello #{params['person']}" end } get '/hello/Frank' assert_equal 'Hello Frank', body end it "supports optional named params like /?:foo?/?:bar?" do mock_app { get '/?:foo?/?:bar?' do "foo=#{params[:foo]};bar=#{params[:bar]}" end } get '/hello/world' assert ok? assert_equal "foo=hello;bar=world", body get '/hello' assert ok? assert_equal "foo=hello;bar=", body get '/hello?bar=baz' assert ok? assert_equal "foo=hello;bar=baz", body get '/' assert ok? assert_equal "foo=;bar=", body end it "uses the default encoding for named params" do mock_app { set :default_encoding ,'ISO-8859-1' get '/:foo/:bar' do "foo=#{params[:foo].encoding};bar=#{params[:bar].encoding}" end } get '/f%C3%B6%C3%B6/b%C3%B6%C3%B6' assert ok? assert_equal 'foo=ISO-8859-1;bar=ISO-8859-1', body end it "supports named captures like %r{/hello/(?<person>[^/?#]+)}" do mock_app { get Regexp.new('/hello/(?<person>[^/?#]+)') do "Hello #{params['person']}" end } get '/hello/Frank' assert_equal 'Hello Frank', body end it "supports optional named captures like %r{/page(?<format>.[^/?#]+)?}" do mock_app { get Regexp.new('/page(?<format>.[^/?#]+)?') do "format=#{params[:format]}" end } get '/page.html' assert ok? assert_equal "format=.html", body get '/page.xml' assert ok? assert_equal "format=.xml", body get '/page' assert ok? assert_equal "format=", body end it 'uses the default encoding for named captures' do mock_app { set :default_encoding ,'ISO-8859-1' get Regexp.new('/page(?<format>.[^/?#]+)?') do "format=#{params[:format].encoding};captures=#{params[:captures][0].encoding}" end } get '/page.f%C3%B6' assert ok? assert_equal 'format=ISO-8859-1;captures=ISO-8859-1', body end it 'does not concatenate params with the same name' do mock_app { get('/:foo') { params[:foo] } } get '/a?foo=b' assert_body 'a' end it "supports single splat params like /*" do mock_app { get '/*' do assert params['splat'].kind_of?(Array) params['splat'].join "\n" end } get '/foo' assert_equal "foo", body get '/foo/bar/baz' assert_equal "foo/bar/baz", body end it "supports mixing multiple splat params like /*/foo/*/*" do mock_app { get '/*/foo/*/*' do assert params['splat'].kind_of?(Array) params['splat'].join "\n" end } get '/bar/foo/bling/baz/boom' assert_equal "bar\nbling\nbaz/boom", body get '/bar/foo/baz' assert not_found? end it "supports mixing named and splat params like /:foo/*" do mock_app { get '/:foo/*' do assert_equal 'foo', params['foo'] assert_equal ['bar/baz'], params['splat'] end } get '/foo/bar/baz' assert ok? end it "matches a dot ('.') as part of a named param" do mock_app { get '/:foo/:bar' do params[:foo] end } get '/user@example.com/name' assert_equal 200, response.status assert_equal 'user@example.com', body end it "matches a literal dot ('.') outside of named params" do mock_app { get '/:file.:ext' do assert_equal 'pony', params[:file] assert_equal 'jpg', params[:ext] 'right on' end } get '/pony.jpg' assert_equal 200, response.status assert_equal 'right on', body end it "literally matches dot in paths" do route_def '/test.bar' get '/test.bar' assert ok? get 'test0bar' assert not_found? end it "literally matches dollar sign in paths" do route_def '/test$/' get '/test$/' assert ok? end it "literally matches plus sign in paths" do route_def '/te+st/' get '/te%2Bst/' assert ok? get '/teeeeeeest/' assert not_found? end it "does not convert plus sign into space as the value of a named param" do mock_app do get '/:test' do params["test"] end end get '/bob+ross' assert ok? assert_equal 'bob+ross', body end it "literally matches parens in paths when escaped" do route_def '/test\(bar\)/' get '/test(bar)/' assert ok? end it "supports basic nested params" do mock_app { get '/hi' do params["person"]["name"] end } get "/hi?person[name]=John+Doe" assert ok? assert_equal "John Doe", body end it "exposes nested params with indifferent hash" do mock_app { get '/testme' do assert_equal 'baz', params['bar']['foo'] assert_equal 'baz', params['bar'][:foo] 'well, alright' end } get '/testme?bar[foo]=baz' assert_equal 'well, alright', body end it "exposes params nested within arrays with indifferent hash" do mock_app { get '/testme' do assert_equal 'baz', params['bar'][0]['foo'] assert_equal 'baz', params['bar'][0][:foo] 'well, alright' end } get '/testme?bar[][foo]=baz' assert_equal 'well, alright', body end it "supports arrays within params" do mock_app { get '/foo' do assert_equal ['A', 'B'], params['bar'] 'looks good' end } get '/foo?bar[]=A&bar[]=B' assert ok? assert_equal 'looks good', body end it "supports deeply nested params" do expected_params = { "emacs" => { "map" => { "goto-line" => "M-g g" }, "version" => "22.3.1" }, "browser" => { "firefox" => {"engine" => {"name"=>"spidermonkey", "version"=>"1.7.0"}}, "chrome" => {"engine" => {"name"=>"V8", "version"=>"1.0"}} }, "paste" => {"name"=>"hello world", "syntax"=>"ruby"} } mock_app { get '/foo' do assert_equal expected_params, params 'looks good' end } get '/foo', expected_params assert ok? assert_equal 'looks good', body end it "preserves non-nested params" do mock_app { get '/foo' do assert_equal "2", params["article_id"] assert_equal "awesome", params['comment']['body'] assert_nil params['comment[body]'] 'looks good' end } get '/foo?article_id=2&comment[body]=awesome' assert ok? assert_equal 'looks good', body end it "matches paths that include spaces encoded with %20" do mock_app { get '/path with spaces' do 'looks good' end } get '/path%20with%20spaces' assert ok? assert_equal 'looks good', body end it "matches paths that include spaces encoded with +" do mock_app { get '/path with spaces' do 'looks good' end } get '/path+with+spaces' assert ok? assert_equal 'looks good', body end it "matches paths that include ampersands" do mock_app { get '/:name' do 'looks good' end } get '/foo&bar' assert ok? assert_equal 'looks good', body end it "URL decodes named parameters and splats" do mock_app { get '/:foo/*' do assert_equal 'hello world', params['foo'] assert_equal ['how are you'], params['splat'] nil end } get '/hello%20world/how%20are%20you' assert ok? end it 'unescapes named parameters and splats' do mock_app { get '/:foo/*' do |a, b| assert_equal "foo\xE2\x80\x8Cbar", params['foo'] assert_predicate params['foo'], :valid_encoding? assert_equal ["bar\xE2\x80\x8Cbaz"], params['splat'] end } get '/foo%e2%80%8cbar/bar%e2%80%8cbaz' assert ok? end it 'supports regular expressions' do mock_app { get(/\/foo...\/bar/) do 'Hello World' end } get '/foooom/bar' assert ok? assert_equal 'Hello World', body end it 'unescapes regular expression captures' do mock_app { get(/\/foo\/(.+)/) do |path| path end } get '/foo/bar%e2%80%8cbaz' assert ok? assert_equal "bar\xE2\x80\x8Cbaz", body assert_predicate body, :valid_encoding? end it 'makes regular expression captures available in params[:captures]' do mock_app { get(/\/fo(.*)\/ba(.*)/) do assert_equal ['orooomma', 'f'], params[:captures] 'right on' end } get '/foorooomma/baf' assert ok? assert_equal 'right on', body end it 'makes regular expression captures available in params[:captures] for concatenated routes' do with_regexp = Mustermann.new('/prefix') + Mustermann.new("/fo(.*)/ba(.*)", type: :regexp) without_regexp = Mustermann.new('/prefix', type: :identity) + Mustermann.new('/baz') mock_app { get(with_regexp) do assert_equal ['orooomma', 'f'], params[:captures] 'right on' end get(without_regexp) do assert !params.keys.include?(:captures) 'no captures here' end } get '/prefix/foorooomma/baf' assert ok? assert_equal 'right on', body get '/prefix/baz' assert ok? assert_equal 'no captures here', body end it 'supports regular expression look-alike routes' do mock_app { get(PatternLookAlike.new) do assert_equal 'this', params[:one] assert_equal 'is', params[:two] assert_equal 'a', params[:three] assert_equal 'test', params[:four] 'right on' end } get '/this/is/a/test/' assert ok? assert_equal 'right on', body end it 'raises a TypeError when pattern is not a String or Regexp' do assert_raises(TypeError) { mock_app { get(42){} } } end it "returns response immediately on halt" do mock_app { get '/' do halt 'Hello World' 'Boo-hoo World' end } get '/' assert ok? assert_equal 'Hello World', body end it "halts with a response tuple" do mock_app { get '/' do halt 295, {'Content-Type' => 'text/plain'}, 'Hello World' end } get '/' assert_equal 295, status assert_equal 'text/plain', response['Content-Type'] assert_equal 'Hello World', body end it "halts with an array of strings" do mock_app { get '/' do halt %w[Hello World How Are You] end } get '/' assert_equal 'HelloWorldHowAreYou', body end it 'sets response.status with halt' do status_was = nil mock_app do after { status_was = status } get('/') { halt 500, 'error' } end get '/' assert_status 500 assert_equal 500, status_was end it "transitions to the next matching route on pass" do mock_app { get '/:foo' do pass 'Hello Foo' end get '/*' do assert !params.include?('foo') 'Hello World' end } get '/bar' assert ok? assert_equal 'Hello World', body end it "makes original request params available in error handler" do mock_app { disable :raise_errors get '/:foo' do raise ArgumentError, "foo" end error do "Hello #{params['foo']}2" end } get '/bar' assert_equal 'Hello bar2', body end it "transitions to 404 when passed and no subsequent route matches" do mock_app { get '/:foo' do pass 'Hello Foo' end } get '/bar' assert not_found? end it "transitions to 404 and sets X-Cascade header when passed and no subsequent route matches" do mock_app { get '/:foo' do pass 'Hello Foo' end get '/bar' do 'Hello Bar' end } get '/foo' assert not_found? assert_equal 'pass', response.headers['X-Cascade'] end it "uses optional block passed to pass as route block if no other route is found" do mock_app { get "/" do pass do "this" end "not this" end } get "/" assert ok? assert "this", body end it "uses optional block passed to pass as route block if no other route is found and superclass has non-matching routes" do base = Class.new(Sinatra::Base) base.get('/foo') { 'foo in baseclass' } mock_app(base) { get "/" do pass do "this" end "not this" end } get "/" assert_equal 200, status assert "this", body end it "passes when matching condition returns false" do mock_app { condition { params[:foo] == 'bar' } get '/:foo' do 'Hello World' end } get '/bar' assert ok? assert_equal 'Hello World', body get '/foo' assert not_found? end it "does not pass when matching condition returns nil" do mock_app { condition { nil } get '/:foo' do 'Hello World' end } get '/bar' assert ok? assert_equal 'Hello World', body end it "passes to next route when condition calls pass explicitly" do mock_app { condition { pass unless params[:foo] == 'bar' } get '/:foo' do 'Hello World' end } get '/bar' assert ok? assert_equal 'Hello World', body get '/foo' assert not_found? end it "passes to the next route when host_name does not match" do mock_app { host_name 'example.com' get '/foo' do 'Hello World' end } get '/foo' assert not_found? get '/foo', {}, { 'HTTP_HOST' => 'example.com' } assert_equal 200, status assert_equal 'Hello World', body end it "passes to the next route when user_agent does not match" do mock_app { user_agent(/Foo/) get '/foo' do 'Hello World' end } get '/foo' assert not_found? get '/foo', {}, { 'HTTP_USER_AGENT' => 'Foo Bar' } assert_equal 200, status assert_equal 'Hello World', body end it "treats missing user agent like an empty string" do mock_app do user_agent(/.*/) get '/' do "Hello World" end end get '/' assert_equal 200, status assert_equal 'Hello World', body end it "makes captures in user agent pattern available in params[:agent]" do mock_app { user_agent(/Foo (.*)/) get '/foo' do 'Hello ' + params[:agent].first end } get '/foo', {}, { 'HTTP_USER_AGENT' => 'Foo Bar' } assert_equal 200, status assert_equal 'Hello Bar', body end it 'matches mime_types with dots, hyphens and plus signs' do mime_types = %w( application/atom+xml application/ecmascript application/EDI-X12 application/EDIFACT application/json application/javascript application/octet-stream application/ogg application/pdf application/postscript application/rdf+xml application/rss+xml application/soap+xml application/font-woff application/xhtml+xml application/xml application/xml-dtd application/xop+xml application/zip application/gzip audio/basic audio/L24 audio/mp4 audio/mpeg audio/ogg audio/vorbis audio/vnd.rn-realaudio audio/vnd.wave audio/webm image/gif image/jpeg image/pjpeg image/png image/svg+xml image/tiff image/vnd.microsoft.icon message/http message/imdn+xml message/partial message/rfc822 model/example model/iges model/mesh model/vrml model/x3d+binary model/x3d+vrml model/x3d+xml multipart/mixed multipart/alternative multipart/related multipart/form-data multipart/signed multipart/encrypted text/cmd text/css text/csv text/html text/javascript application/javascript text/plain text/vcard text/xml video/mpeg video/mp4 video/ogg video/quicktime video/webm video/x-matroska video/x-ms-wmv video/x-flv application/vnd.oasis.opendocument.text application/vnd.oasis.opendocument.spreadsheet application/vnd.oasis.opendocument.presentation application/vnd.oasis.opendocument.graphics application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet application/vnd.ms-powerpoint application/vnd.openxmlformats-officedocument.presentationml.presentation application/vnd.openxmlformats-officedocument.wordprocessingml.document application/vnd.mozilla.xul+xml application/vnd.google-earth.kml+xml application/x-deb application/x-dvi application/x-font-ttf application/x-javascript application/x-latex application/x-mpegURL application/x-rar-compressed application/x-shockwave-flash application/x-stuffit application/x-tar application/x-www-form-urlencoded application/x-xpinstall audio/x-aac audio/x-caf image/x-xcf text/x-gwt-rpc text/x-jquery-tmpl application/x-pkcs12 application/x-pkcs12 application/x-pkcs7-certificates application/x-pkcs7-certificates application/x-pkcs7-certreqresp application/x-pkcs7-mime application/x-pkcs7-mime application/x-pkcs7-signature ) mime_types.each { |mime_type| assert mime_type.match(Sinatra::Request::HEADER_VALUE_WITH_PARAMS) } end it "filters by accept header" do mock_app { get '/', :provides => :xml do env['HTTP_ACCEPT'] end get '/foo', :provides => :html do env['HTTP_ACCEPT'] end get '/stream', :provides => 'text/event-stream' do env['HTTP_ACCEPT'] end } get '/', {}, { 'HTTP_ACCEPT' => 'application/xml' } assert ok? assert_equal 'application/xml', body assert_equal 'application/xml;charset=utf-8', response.headers['Content-Type'] get '/', {}, {} assert ok? assert_equal '', body assert_equal 'application/xml;charset=utf-8', response.headers['Content-Type'] get '/', {}, { 'HTTP_ACCEPT' => '*/*' } assert ok? assert_equal '*/*', body assert_equal 'application/xml;charset=utf-8', response.headers['Content-Type'] get '/', {}, { 'HTTP_ACCEPT' => 'text/html;q=0.9' } assert !ok? get '/foo', {}, { 'HTTP_ACCEPT' => 'text/html;q=0.9' } assert ok? assert_equal 'text/html;q=0.9', body get '/foo', {}, { 'HTTP_ACCEPT' => '' } assert ok? assert_equal '', body get '/foo', {}, { 'HTTP_ACCEPT' => '*/*' } assert ok? assert_equal '*/*', body get '/foo', {}, { 'HTTP_ACCEPT' => 'application/xml' } assert !ok? get '/stream', {}, { 'HTTP_ACCEPT' => 'text/event-stream' } assert ok? assert_equal 'text/event-stream', body get '/stream', {}, { 'HTTP_ACCEPT' => '' } assert ok? assert_equal '', body get '/stream', {}, { 'HTTP_ACCEPT' => '*/*' } assert ok? assert_equal '*/*', body get '/stream', {}, { 'HTTP_ACCEPT' => 'application/xml' } assert !ok? end it "filters by current Content-Type" do mock_app do before('/txt') { content_type :txt } get('*', :provides => :txt) { 'txt' } before('/html') { content_type :html } get('*', :provides => :html) { 'html' } end get '/', {}, { 'HTTP_ACCEPT' => '*/*' } assert ok? assert_equal 'text/plain;charset=utf-8', response.headers['Content-Type'] assert_body 'txt' get '/txt', {}, { 'HTTP_ACCEPT' => 'text/plain' } assert ok? assert_equal 'text/plain;charset=utf-8', response.headers['Content-Type'] assert_body 'txt' get '/', {}, { 'HTTP_ACCEPT' => 'text/html' } assert ok? assert_equal 'text/html;charset=utf-8', response.headers['Content-Type'] assert_body 'html' end it "doesn't allow provides of passed routes to interfere with provides of other routes" do mock_app do get('/:foo', :provides => :txt) do pass if params[:foo] != 'foo' 'foo' end get('/bar', :provides => :html) { 'bar' } end get '/foo', {}, { 'HTTP_ACCEPT' => '*/*' } assert ok? assert_equal 'text/plain;charset=utf-8', response.headers['Content-Type'] assert_body 'foo' get '/bar', {}, { 'HTTP_ACCEPT' => '*/*' } assert ok? assert_equal 'text/html;charset=utf-8', response.headers['Content-Type'] assert_body 'bar' end it "allows multiple mime types for accept header" do types = ['image/jpeg', 'image/pjpeg'] mock_app { get '/', :provides => types do env['HTTP_ACCEPT'] end } types.each do |type| get '/', {}, { 'HTTP_ACCEPT' => type } assert ok? assert_equal type, body assert_equal type, response.headers['Content-Type'] end end it 'respects user agent preferences for the content type' do mock_app { get('/', :provides => [:png, :html]) { content_type }} get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5,text/html;q=0.8' } assert_body 'text/html;charset=utf-8' get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.8,text/html;q=0.5' } assert_body 'image/png' end it 'accepts generic types' do mock_app do get('/', :provides => :xml) { content_type } get('/') { 'no match' } end get '/', {}, { 'HTTP_ACCEPT' => 'foo/*' } assert_body 'no match' get '/', {}, { 'HTTP_ACCEPT' => 'application/*' } assert_body 'application/xml;charset=utf-8' get '/', {}, { 'HTTP_ACCEPT' => '*/*' } assert_body 'application/xml;charset=utf-8' end it 'prefers concrete over partly generic types' do mock_app { get('/', :provides => [:png, :html]) { content_type }} get '/', {}, { 'HTTP_ACCEPT' => 'image/*, text/html' } assert_body 'text/html;charset=utf-8' get '/', {}, { 'HTTP_ACCEPT' => 'image/png, text/*' } assert_body 'image/png' end it 'prefers concrete over fully generic types' do mock_app { get('/', :provides => [:png, :html]) { content_type }} get '/', {}, { 'HTTP_ACCEPT' => '*/*, text/html' } assert_body 'text/html;charset=utf-8' get '/', {}, { 'HTTP_ACCEPT' => 'image/png, */*' } assert_body 'image/png' end it 'prefers partly generic over fully generic types' do mock_app { get('/', :provides => [:png, :html]) { content_type }} get '/', {}, { 'HTTP_ACCEPT' => '*/*, text/*' } assert_body 'text/html;charset=utf-8' get '/', {}, { 'HTTP_ACCEPT' => 'image/*, */*' } assert_body 'image/png' end it 'respects quality with generic types' do mock_app { get('/', :provides => [:png, :html]) { content_type }} get '/', {}, { 'HTTP_ACCEPT' => 'image/*;q=1, text/html;q=0' } assert_body 'image/png' get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5, text/*;q=0.7' } assert_body 'text/html;charset=utf-8' end it 'supplies a default quality of 1.0' do mock_app { get('/', :provides => [:png, :html]) { content_type }} get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5, text/*' } assert_body 'text/html;charset=utf-8' end it 'orders types with equal quality by parameter count' do mock_app do get('/', :provides => [:png, :jpg]) { content_type } end lo_png = 'image/png;q=0.5' hi_png = 'image/png;q=0.5;profile=FOGRA40;gamma=0.8' jpeg = 'image/jpeg;q=0.5;compress=0.25' get '/', {}, { 'HTTP_ACCEPT' => "#{lo_png}, #{jpeg}" } assert_body 'image/jpeg' get '/', {}, { 'HTTP_ACCEPT' => "#{hi_png}, #{jpeg}" } assert_body 'image/png' end it 'ignores the quality parameter when ordering by parameter count' do mock_app do get('/', :provides => [:png, :jpg]) { content_type } end lo_png = 'image/png' hi_png = 'image/png;profile=FOGRA40;gamma=0.8' jpeg = 'image/jpeg;q=1.0;compress=0.25' get '/', {}, { 'HTTP_ACCEPT' => "#{jpeg}, #{lo_png}" } assert_body 'image/jpeg' get '/', {}, { 'HTTP_ACCEPT' => "#{jpeg}, #{hi_png}" } assert_body 'image/png' end it 'properly handles quoted strings in parameters' do mock_app do get('/', :provides => [:png, :jpg]) { content_type } end get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5;profile=",image/jpeg,"' } assert_body 'image/png' get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5,image/jpeg;q=0;x=";q=1.0"' } assert_body 'image/png' get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5,image/jpeg;q=0;x="\";q=1.0"' } assert_body 'image/png' end it 'accepts both text/javascript and application/javascript for js' do mock_app { get('/', :provides => :js) { content_type }} get '/', {}, { 'HTTP_ACCEPT' => 'application/javascript' } assert_body 'application/javascript;charset=utf-8' get '/', {}, { 'HTTP_ACCEPT' => 'text/javascript' } assert_body 'text/javascript;charset=utf-8' end it 'accepts both text/xml and application/xml for xml' do mock_app { get('/', :provides => :xml) { content_type }} get '/', {}, { 'HTTP_ACCEPT' => 'application/xml' } assert_body 'application/xml;charset=utf-8'
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
true
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/static_test.rb
test/static_test.rb
require_relative 'test_helper' class StaticTest < Minitest::Test setup do mock_app do set :static, true set :public_folder, __dir__ end end it 'serves GET requests for files in the public directory' do get "/#{File.basename(__FILE__)}" assert ok? assert_equal File.read(__FILE__), body assert_equal File.size(__FILE__).to_s, response['Content-Length'] assert response.headers.include?('Last-Modified') end it 'produces a body that can be iterated over multiple times' do env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}") _, _, body = @app.call(env) buf1, buf2 = [], [] body.each { |part| buf1 << part } body.each { |part| buf2 << part } assert_equal buf1.join, buf2.join assert_equal File.read(__FILE__), buf1.join end it 'sets the sinatra.static_file env variable if served' do env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}") @app.call(env) assert_equal File.expand_path(__FILE__), env['sinatra.static_file'] end it 'serves HEAD requests for files in the public directory' do head "/#{File.basename(__FILE__)}" assert ok? assert_equal '', body assert response.headers.include?('Last-Modified') assert_equal File.size(__FILE__).to_s, response['Content-Length'] end %w[POST PUT DELETE].each do |verb| it "does not serve #{verb} requests" do send verb.downcase, "/#{File.basename(__FILE__)}" assert_equal 404, status end end it 'serves files in preference to custom routes' do @app.get("/#{File.basename(__FILE__)}") { 'Hello World' } get "/#{File.basename(__FILE__)}" assert ok? assert body != 'Hello World' end it 'does not serve directories' do get "/" assert not_found? end it 'passes to the next handler when the path contains null bytes' do get "/foo%00" assert not_found? end it 'passes to the next handler when the static option is disabled' do @app.set :static, false get "/#{File.basename(__FILE__)}" assert not_found? end it 'passes to the next handler when the public option is nil' do @app.set :public_folder, nil get "/#{File.basename(__FILE__)}" assert not_found? end it '404s when a file is not found' do get "/foobarbaz.txt" assert not_found? end it 'there is no path is 404 error pages' do env = Rack::MockRequest.env_for("/dummy").tap { |env| env["PATH_INFO"] = "/<script>" } _, _, body = @app.call(env) assert_equal(["<h1>Not Found</h1>"], body, "Unexpected response content.") end it 'serves files when .. path traverses within public directory' do get "/data/../#{File.basename(__FILE__)}" assert ok? assert_equal File.read(__FILE__), body end it '404s when .. path traverses outside of public directory' do mock_app do set :static, true set :public_folder, __dir__ + '/data' disable :protection end get "/../#{File.basename(__FILE__)}" assert not_found? end def assert_valid_range(http_range, range, path, file) request = Rack::MockRequest.new(@app) response = request.get("/#{File.basename(path)}", 'HTTP_RANGE' => http_range) should_be = file[range] expected_range = "bytes #{range.begin}-#{range.end}/#{file.length}" assert_equal( 206,response.status, "Should be HTTP/1.1 206 Partial content" ) assert_equal( should_be.length, response.body.length, "Unexpected response length for #{http_range}" ) assert_equal( should_be, response.body, "Unexpected response data for #{http_range}" ) assert_equal( should_be.length.to_s, response['Content-Length'], "Incorrect Content-Length for #{http_range}" ) assert_equal( expected_range, response['Content-Range'], "Incorrect Content-Range for #{http_range}" ) end it 'handles valid byte ranges correctly' do # Use the biggest file in this dir so we can test ranges > 8k bytes. (StaticFile sends in 8k chunks.) path = __dir__ + '/helpers_test.rb' # currently 16k bytes file = File.read(path) length = file.length assert length > 9000, "The test file #{path} is too short (#{length} bytes) to run these tests" [0..0, 42..88, 1234..1234, 100..9000, 0..(length-1), (length-1)..(length-1)].each do |range| assert_valid_range("bytes=#{range.begin}-#{range.end}", range, path, file) end [0, 100, length-100, length-1].each do |start| assert_valid_range("bytes=#{start}-", (start..length-1), path, file) end [1, 100, length-100, length-1, length].each do |range_length| assert_valid_range("bytes=-#{range_length}", (length-range_length..length-1), path, file) end # Some valid ranges that exceed the length of the file: assert_valid_range("bytes=100-999999", (100..length-1), path, file) assert_valid_range("bytes=100-#{length}", (100..length-1), path, file) assert_valid_range("bytes=-#{length}", (0..length-1), path, file) assert_valid_range("bytes=-#{length+1}", (0..length-1), path, file) assert_valid_range("bytes=-999999", (0..length-1), path, file) end it 'correctly ignores syntactically invalid range requests' do ["bytes=45-40", "octets=10-20", "bytes=", "bytes=3-1,4-5"].each do |http_range| request = Rack::MockRequest.new(@app) response = request.get("/#{File.basename(__FILE__)}", 'HTTP_RANGE' => http_range) assert_equal( 200, response.status, "Invalid range '#{http_range}' should be ignored" ) assert_nil( response['Content-Range'], "Invalid range '#{http_range}' should be ignored" ) end end it 'returns error 416 for unsatisfiable range requests' do # An unsatisfiable request is one that specifies a start that's at or past the end of the file. length = File.read(__FILE__).length ["bytes=888888-", "bytes=888888-999999", "bytes=#{length}-#{length}"].each do |http_range| request = Rack::MockRequest.new(@app) response = request.get("/#{File.basename(__FILE__)}", 'HTTP_RANGE' => http_range) assert_equal( 416, response.status, "Unsatisfiable range '#{http_range}' should return 416" ) assert_equal( "bytes */#{length}", response['Content-Range'], "416 response should include actual length" ) end end it 'does not include static cache control headers by default' do env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}") _, headers, _ = @app.call(env) assert !headers.has_key?('Cache-Control') end it 'sets cache control headers on static files if set' do @app.set :static_cache_control, :public env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}") _, headers, _ = @app.call(env) assert headers.has_key?('Cache-Control') assert_equal headers['Cache-Control'], 'public' @app.set( :static_cache_control, [:public, :must_revalidate, {:max_age => 300}] ) env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}") _, headers, _ = @app.call(env) assert headers.has_key?('Cache-Control') assert_equal( headers['Cache-Control'], 'public, must-revalidate, max-age=300' ) end it 'renders static assets with custom status via options' do mock_app do set :static, true set :public_folder, __dir__ post '/*' do static!(:status => params[:status]) end end post "/#{File.basename(__FILE__)}?status=422" assert_equal response.status, 422 assert_equal File.read(__FILE__), body assert_equal File.size(__FILE__).to_s, response['Content-Length'] assert response.headers.include?('Last-Modified') end it 'serves files with a + sign in the path' do mock_app do set :static, true set :public_folder, File.join(__dir__, 'public') end get "/hello+world.txt" real_path = File.join(__dir__, 'public', 'hello+world.txt') assert ok? assert_equal File.read(real_path), body assert_equal File.size(real_path).to_s, response['Content-Length'] assert response.headers.include?('Last-Modified') end it 'serves files with a URL encoded + sign (%2B) in the path' do mock_app do set :static, true set :public_folder, File.join(__dir__, 'public') end get "/hello%2bworld.txt" real_path = File.join(__dir__, 'public', 'hello+world.txt') assert ok? assert_equal File.read(real_path), body assert_equal File.size(real_path).to_s, response['Content-Length'] assert response.headers.include?('Last-Modified') end it 'applies custom headers defined in static_headers setting' do mock_app do set :static, true set :public_folder, __dir__ set :static_headers, { 'access-control-allow-origin' => '*', 'x-static-test' => 'yes' } end get "/#{File.basename(__FILE__)}" assert ok? assert_equal '*', response['access-control-allow-origin'] assert_equal 'yes', response['x-static-test'] end it 'respects both static_cache_control and static_headers settings together' do mock_app do set :static, true set :public_folder, __dir__ set :static_cache_control, [:public, max_age: 3600] set :static_headers, { 'x-static-test' => 'yes' } end get "/#{File.basename(__FILE__)}" assert ok? assert_equal 'yes', response['x-static-test'] assert_includes response['cache-control'], 'public' assert_match(/max-age=3600/, response['cache-control']) end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/response_test.rb
test/response_test.rb
require_relative 'test_helper' class ResponseTest < Minitest::Test setup { @response = Sinatra::Response.new([], 200, { 'Content-Type' => 'text/html' }) } def assert_same_body(a, b) assert_equal a.to_enum(:each).to_a, b.to_enum(:each).to_a end it "initializes with 200, text/html, and empty body" do assert_equal 200, @response.status assert_equal 'text/html', @response['Content-Type'] assert_equal [], @response.body end it 'uses case insensitive headers' do @response['content-type'] = 'application/foo' assert_equal 'application/foo', @response['Content-Type'] assert_equal 'application/foo', @response['CONTENT-TYPE'] end it 'writes to body' do @response.body = 'Hello' @response.write ' World' assert_equal 'Hello World', @response.body.join end [204, 304].each do |status_code| it "removes the Content-Type header and body when response status is #{status_code}" do @response.status = status_code @response.body = ['Hello World'] assert_equal [status_code, {}, []], @response.finish end end [200, 201, 202, 301, 302, 400, 401, 403, 404, 500].each do |status_code| it "will not removes the Content-Type header and body when response status is #{status_code}" do @response.status = status_code @response.body = ['Hello World'] assert_equal [ status_code, { 'content-type' => 'text/html', 'content-length' => '11' }, ['Hello World'] ], @response.finish end end it 'Calculates the Content-Length using the bytesize of the body' do @response.body = ['Hello', 'World!', '✈'] _, headers, body = @response.finish assert_equal '14', headers['Content-Length'] assert_same_body @response.body, body end it 'does not call #to_ary or #inject on the body' do object = Object.new def object.inject(*) fail 'called' end def object.to_ary(*) fail 'called' end def object.each(*) end @response.body = object assert @response.finish end it 'does not nest a Sinatra::Response' do @response.body = Sinatra::Response.new ["foo"] assert_same_body @response.body, ["foo"] end it 'does not nest a Rack::Response' do @response.body = Rack::Response.new ["foo"] assert_same_body @response.body, ["foo"] end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/integration_async_helper.rb
test/integration_async_helper.rb
require File.expand_path('integration_helper', __dir__) module IntegrationAsyncHelper Server = IntegrationHelper::BaseServer def it(message, &block) Server.all_async.each do |server| next unless server.installed? super("with #{server.name}: #{message}") { server.run_test(self, &block) } end end def self.extend_object(obj) super base_port = 5100 + Process.pid % 100 servers = %w(puma) servers.each_with_index do |server, index| Server.run(server, base_port+index, async: true) end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/extensions_test.rb
test/extensions_test.rb
require_relative 'test_helper' class ExtensionsTest < Minitest::Test module FooExtensions def foo end private def im_hiding_in_ur_foos end end module BarExtensions def bar end end module BazExtensions def baz end end module QuuxExtensions def quux end end module PainExtensions def foo=(name); end def bar?(name); end def fizz!(name); end end it 'will add the methods to the DSL for the class in which you register them and its subclasses' do Sinatra::Base.register FooExtensions assert Sinatra::Base.respond_to?(:foo) Sinatra::Application.register BarExtensions assert Sinatra::Application.respond_to?(:bar) assert Sinatra::Application.respond_to?(:foo) assert !Sinatra::Base.respond_to?(:bar) end it 'allows extending by passing a block' do Sinatra::Base.register { def im_in_ur_anonymous_module; end } assert Sinatra::Base.respond_to?(:im_in_ur_anonymous_module) end it 'will make sure any public methods added via Application#register are delegated to Sinatra::Delegator' do Sinatra::Application.register FooExtensions assert Sinatra::Delegator.private_instance_methods. map { |m| m.to_sym }.include?(:foo) assert !Sinatra::Delegator.private_instance_methods. map { |m| m.to_sym }.include?(:im_hiding_in_ur_foos) end it 'will handle special method names' do Sinatra::Application.register PainExtensions assert Sinatra::Delegator.private_instance_methods. map { |m| m.to_sym }.include?(:foo=) assert Sinatra::Delegator.private_instance_methods. map { |m| m.to_sym }.include?(:bar?) assert Sinatra::Delegator.private_instance_methods. map { |m| m.to_sym }.include?(:fizz!) end it 'will not delegate methods on Base#register' do Sinatra::Base.register QuuxExtensions assert !Sinatra::Delegator.private_instance_methods.include?("quux") end it 'will extend the Sinatra::Application application by default' do Sinatra.register BazExtensions assert !Sinatra::Base.respond_to?(:baz) assert Sinatra::Application.respond_to?(:baz) end module BizzleExtension def bizzle bizzle_option end def self.registered(base) fail "base should be BizzleApp" unless base == BizzleApp fail "base should have already extended BizzleExtension" unless base.respond_to?(:bizzle) base.set :bizzle_option, 'bizzle!' end end class BizzleApp < Sinatra::Base end it 'sends .registered to the extension module after extending the class' do BizzleApp.register BizzleExtension assert_equal 'bizzle!', BizzleApp.bizzle_option assert_equal 'bizzle!', BizzleApp.bizzle end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/test_helper.rb
test/test_helper.rb
if ENV['COVERAGE'] require 'simplecov' SimpleCov.start do add_filter '/test/' add_group 'sinatra-contrib', 'sinatra-contrib' add_group 'rack-protection', 'rack-protection' end end ENV['APP_ENV'] = 'test' require 'rack' testdir = __dir__ $LOAD_PATH.unshift testdir unless $LOAD_PATH.include?(testdir) libdir = File.dirname(__dir__) + '/lib' $LOAD_PATH.unshift libdir unless $LOAD_PATH.include?(libdir) require 'minitest' require 'contest' require 'rack/test' # Some of ActiveSupport's core extensions to Hash get loaded during internal # testing (e.g. by RABL and our RABL test) that we have no control over, but we # need them to load *before* Sinatra::IndifferentHash (which is itself loaded # by Sinatra::Base) whenever the full test suite is executed, so we'll do it # preemptively here. # # Newer Rubies have these methods built-in, so the extensions are no-ops. require 'active_support/core_ext/hash/conversions' require 'active_support/core_ext/hash/slice' require 'active_support/core_ext/hash/keys' require 'sinatra/base' class Sinatra::Base include Minitest::Assertions # Allow assertions in request context def assertions @assertions ||= 0 end attr_writer :assertions end class Rack::Builder def include?(middleware) @ins.any? { |m| middleware === m } end end Sinatra::Base.set :environment, :test class Minitest::Test include Rack::Test::Methods class << self alias_method :it, :test alias_method :section, :context end def self.example(desc = nil, &block) @example_count = 0 unless instance_variable_defined? :@example_count @example_count += 1 it(desc || "Example #{@example_count}", &block) end alias_method :response, :last_response setup do Sinatra::Base.set :environment, :test end # Sets up a Sinatra::Base subclass defined with the block # given. Used in setup or individual spec methods to establish # the application. def mock_app(base=Sinatra::Base, &block) @app = Sinatra.new(base, &block) end def app Rack::Lint.new(@app) end def body response.body.to_s end def assert_body(value) if value.respond_to? :to_str assert_equal value.lstrip.gsub(/\s*\n\s*/, ""), body.lstrip.gsub(/\s*\n\s*/, "") else assert_match value, body end end def assert_status(expected) assert_equal Integer(expected), Integer(status) end def assert_like(a,b) pattern = /id=['"][^"']*["']|\s+/ assert_equal a.strip.gsub(pattern, ""), b.strip.gsub(pattern, "") end def assert_include(str, substr) assert str.include?(substr), "expected #{str.inspect} to include #{substr.inspect}" end def options(uri, params = {}, env = {}, &block) request(uri, env.merge(:method => "OPTIONS", :params => params), &block) end def patch(uri, params = {}, env = {}, &block) request(uri, env.merge(:method => "PATCH", :params => params), &block) end def link(uri, params = {}, env = {}, &block) request(uri, env.merge(:method => "LINK", :params => params), &block) end def unlink(uri, params = {}, env = {}, &block) request(uri, env.merge(:method => "UNLINK", :params => params), &block) end # Delegate other missing methods to response. def method_missing(name, *args, &block) if response && response.respond_to?(name) response.send(name, *args, &block) else super end rescue Rack::Test::Error super end # Do not output warnings for the duration of the block. def silence_warnings $VERBOSE, v = nil, $VERBOSE yield ensure $VERBOSE = v end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/request_test.rb
test/request_test.rb
require_relative 'test_helper' require 'stringio' class RequestTest < Minitest::Test it 'responds to #user_agent' do request = Sinatra::Request.new({'HTTP_USER_AGENT' => 'Test'}) assert request.respond_to?(:user_agent) assert_equal 'Test', request.user_agent end it 'parses POST params when Content-Type is form-dataish' do request = Sinatra::Request.new( 'REQUEST_METHOD' => 'PUT', 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', 'rack.input' => StringIO.new('foo=bar') ) assert_equal 'bar', request.params['foo'] end it 'raises Sinatra::BadRequest when multipart/form-data request has no content' do request = Sinatra::Request.new( 'REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'multipart/form-data; boundary=dummy', 'rack.input' => StringIO.new('') ) assert_raises(Sinatra::BadRequest) { request.params } end it 'is secure when the url scheme is https' do request = Sinatra::Request.new('rack.url_scheme' => 'https') assert request.secure? end it 'is not secure when the url scheme is http' do request = Sinatra::Request.new('rack.url_scheme' => 'http') assert !request.secure? end it 'respects X-Forwarded-Host header' do request = Sinatra::Request.new('HTTP_X_FORWARDED_HOST' => 'example.com') assert request.forwarded? end it 'respects Forwarded header with host key' do request = Sinatra::Request.new('HTTP_FORWARDED' => 'host=example.com') assert request.forwarded? request = Sinatra::Request.new('HTTP_FORWARDED' => 'for=192.0.2.60;proto=http;by=203.0.113.43') refute request.forwarded? end it 'respects X-Forwarded-Proto header for proxied SSL' do request = Sinatra::Request.new('HTTP_X_FORWARDED_PROTO' => 'https') assert request.secure? end it 'is possible to marshal params' do request = Sinatra::Request.new( 'REQUEST_METHOD' => 'PUT', 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', 'rack.input' => StringIO.new('foo=bar') ) Sinatra::IndifferentHash[request.params] dumped = Marshal.dump(request.params) assert_equal 'bar', Marshal.load(dumped)['foo'] end it "exposes the preferred type's parameters" do request = Sinatra::Request.new( 'HTTP_ACCEPT' => 'image/jpeg; compress=0.25' ) assert_equal({ 'compress' => '0.25' }, request.preferred_type.params) end it "raises Sinatra::BadRequest when params contain conflicting types" do request = Sinatra::Request.new 'QUERY_STRING' => 'foo=&foo[]=' assert_raises(Sinatra::BadRequest) { request.params } end it "makes accept types behave like strings" do request = Sinatra::Request.new('HTTP_ACCEPT' => 'image/jpeg; compress=0.25') assert request.accept?('image/jpeg') assert_equal 'image/jpeg', request.preferred_type.to_s assert_equal 'image/jpeg; compress=0.25', request.preferred_type.to_s(true) assert_equal 'image/jpeg', request.preferred_type.to_str assert_equal 'image', request.preferred_type.split('/').first String.instance_methods.each do |method| next unless "".respond_to? method assert request.preferred_type.respond_to?(method), "responds to #{method}" end end it "accepts types when wildcards are requested" do request = Sinatra::Request.new('HTTP_ACCEPT' => 'image/*') assert request.accept?('image/jpeg') end it "properly decodes MIME type parameters" do request = Sinatra::Request.new( 'HTTP_ACCEPT' => 'image/jpeg;unquoted=0.25;quoted="0.25";chartest="\";,\x"' ) expected = { 'unquoted' => '0.25', 'quoted' => '0.25', 'chartest' => '";,x' } assert_equal(expected, request.preferred_type.params) end it 'accepts */* when HTTP_ACCEPT is not present in the request' do request = Sinatra::Request.new Hash.new assert_equal 1, request.accept.size assert request.accept?('text/html') assert_equal '*/*', request.preferred_type.to_s assert_equal '*/*', request.preferred_type.to_s(true) end it 'accepts */* when HTTP_ACCEPT is blank in the request' do request = Sinatra::Request.new 'HTTP_ACCEPT' => '' assert_equal 1, request.accept.size assert request.accept?('text/html') assert_equal '*/*', request.preferred_type.to_s assert_equal '*/*', request.preferred_type.to_s(true) end it 'will not accept types not specified in HTTP_ACCEPT when HTTP_ACCEPT is provided' do request = Sinatra::Request.new 'HTTP_ACCEPT' => 'application/json' assert !request.accept?('text/html') end it 'will accept types that fulfill HTTP_ACCEPT parameters' do request = Sinatra::Request.new 'HTTP_ACCEPT' => 'application/rss+xml; version="http://purl.org/rss/1.0/"' assert request.accept?('application/rss+xml; version="http://purl.org/rss/1.0/"') assert request.accept?('application/rss+xml; version="http://purl.org/rss/1.0/"; charset=utf-8') assert !request.accept?('application/rss+xml; version="https://cyber.harvard.edu/rss/rss.html"') end it 'will accept more generic types that include HTTP_ACCEPT parameters' do request = Sinatra::Request.new 'HTTP_ACCEPT' => 'application/rss+xml; charset=utf-8; version="http://purl.org/rss/1.0/"' assert request.accept?('application/rss+xml') assert request.accept?('application/rss+xml; version="http://purl.org/rss/1.0/"') end it 'will accept types matching HTTP_ACCEPT when parameters in arbitrary order' do request = Sinatra::Request.new 'HTTP_ACCEPT' => 'application/rss+xml; charset=utf-8; version="http://purl.org/rss/1.0/"' assert request.accept?('application/rss+xml; version="http://purl.org/rss/1.0/"; charset=utf-8') end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/integration_start_test.rb
test/integration_start_test.rb
require_relative "integration_start_helper" class IntegrationStartTest < Minitest::Test include IntegrationStartHelper # what we test here: that the correct help text is printed when the required gems aren't installed def test_app_start_without_rackup # Why we skip head versions: The Gemfile used here would have to support # the ENVs and we would need to bundle before starting the app # # Example from locally playing with this: # # root@df8b1e7cb106:/app# rack_session=head BUNDLE_GEMFILE=./test/integration/gemfile_without_rackup.rb ruby ./test/integration/simple_app.rb -p 0 -s puma # The git source https://github.com/rack/rack-session.git is not yet checked out. Please run `bundle install` before trying to start your application # # Using bundler/inline is an idea, but it would add to the startup time skip "So much work to run with rack head branch" if ENV['rack'] == 'head' skip "So much work to run with rack-session head branch" if ENV['rack_session'] == 'head' app_file = File.join(__dir__, "integration", "simple_app.rb") gem_file = File.join(__dir__, "integration", "gemfile_without_rackup.rb") lock_file = File.join(__dir__, "integration", "gemfile_without_rackup.rb.lock") command = command_for(app_file) env = { "BUNDLE_GEMFILE" => gem_file } with_process(command: command, env: env) do |process, read_io| assert wait_for_output(read_io, /Sinatra could not start, the required gems weren't found/) end # this ensure block runs even if the test is skipped ensure # when the command is run, at least with bundler 2.6.9, test/integration/gemfile_without_rackup.rb.lock is created # we need to clean it up to avoid problems on consecutive runs File.delete(lock_file) if lock_file && File.exist?(lock_file) end def test_classic_app_start app_file = File.join(__dir__, "integration", "simple_app.rb") command = command_for(app_file) with_process(command: command) do |process, read_io| assert wait_for_output(read_io, /Sinatra \(v.+\) has taken the stage/) end end def test_classic_app_with_zeitwerk app_file = File.join(__dir__, "integration", "zeitwerk_app.rb") command = command_for(app_file) with_process(command: command) do |process, read_io| assert wait_for_output(read_io, /Sinatra \(v.+\) has taken the stage/) end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/delegator_test.rb
test/delegator_test.rb
require_relative 'test_helper' class DelegatorTest < Minitest::Test class Mirror attr_reader :last_call def method_missing(*a, &b) @last_call = [*a.map(&:to_s)] @last_call << b if b end end def self.delegates(name) it "delegates #{name}" do m = mirror { send name } assert_equal [name.to_s], m.last_call end it "delegates #{name} with arguments" do m = mirror { send name, "foo", "bar" } assert_equal [name.to_s, "foo", "bar"], m.last_call end it "delegates #{name} with block" do block = proc { } m = mirror { send(name, &block) } assert_equal [name.to_s, block], m.last_call end end setup do @target_was = Sinatra::Delegator.target end def teardown Sinatra::Delegator.target = @target_was end def delegation_app(&block) mock_app { Sinatra::Delegator.target = self } delegate(&block) end def mirror(&block) mirror = Mirror.new Sinatra::Delegator.target = mirror delegate(&block) end def delegate(&block) assert Sinatra::Delegator.target != Sinatra::Application Object.new.extend(Sinatra::Delegator).instance_eval(&block) if block Sinatra::Delegator.target end def target Sinatra::Delegator.target end it 'defaults to Sinatra::Application as target' do assert_equal Sinatra::Application, Sinatra::Delegator.target end %w[get put post delete options patch link unlink].each do |verb| it "delegates #{verb} correctly" do delegation_app do send(verb, '/hello') { 'Hello World' } end request = Rack::MockRequest.new(@app) response = request.request(verb.upcase, '/hello', {}) assert response.ok? assert_equal 'Hello World', response.body end end it "delegates head correctly" do delegation_app do head '/hello' do response['X-Hello'] = 'World!' 'remove me' end end request = Rack::MockRequest.new(@app) response = request.request('HEAD', '/hello', {}) assert response.ok? assert_equal 'World!', response['X-Hello'] assert_equal '', response.body end it "delegates before with keyword arguments correctly" do delegation_app do set(:foo) do |something| something end before(foo: 'bar') do :nothing end end end it "registers extensions with the delegation target" do app, mixin = mirror, Module.new Sinatra.register mixin assert_equal ["register", mixin.to_s], app.last_call end it "registers helpers with the delegation target" do app, mixin = mirror, Module.new Sinatra.helpers mixin assert_equal ["helpers", mixin.to_s], app.last_call end it "registers middleware with the delegation target" do app, mixin = mirror, Module.new Sinatra.use mixin assert_equal ["use", mixin.to_s], app.last_call end it "should work with method_missing proxies for options" do mixin = Module.new do def respond_to?(method, *) method.to_sym == :options or super end def method_missing(method, *args, &block) return super unless method.to_sym == :options {:some => :option} end end value = nil mirror do extend mixin value = options end assert_equal({:some => :option}, value) end it "delegates crazy method names" do Sinatra::Delegator.delegate "foo:bar:" method = mirror { send "foo:bar:" }.last_call.first assert_equal "foo:bar:", method end delegates 'get' delegates 'patch' delegates 'put' delegates 'post' delegates 'delete' delegates 'head' delegates 'options' delegates 'template' delegates 'layout' delegates 'before' delegates 'after' delegates 'error' delegates 'not_found' delegates 'configure' delegates 'set' delegates 'mime_type' delegates 'enable' delegates 'disable' delegates 'use' delegates 'development?' delegates 'test?' delegates 'production?' delegates 'helpers' delegates 'settings' end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/builder_test.rb
test/builder_test.rb
require_relative 'test_helper' begin require 'builder' class BuilderTest < Minitest::Test def builder_app(options = {}, &block) mock_app do set :views, __dir__ + '/views' set options get('/', &block) end get '/' end it 'renders inline Builder strings' do builder_app { builder 'xml.instruct!' } assert ok? assert_equal %{<?xml version="1.0" encoding="UTF-8"?>\n}, body end it 'defaults content type to xml' do builder_app { builder 'xml.instruct!' } assert ok? assert_equal "application/xml;charset=utf-8", response['Content-Type'] end it 'defaults allows setting content type per route' do builder_app do content_type :html builder 'xml.instruct!' end assert ok? assert_equal "text/html;charset=utf-8", response['Content-Type'] end it 'defaults allows setting content type globally' do builder_app(:builder => { :content_type => 'html' }) do builder 'xml.instruct!' end assert ok? assert_equal "text/html;charset=utf-8", response['Content-Type'] end it 'renders inline blocks' do builder_app do @name = "Frank & Mary" builder { |xml| xml.couple @name } end assert ok? assert_equal "<couple>Frank &amp; Mary</couple>\n", body end it 'renders .builder files in views path' do builder_app do @name = "Blue" builder :hello end assert ok? assert_equal %(<exclaim>You're my boy, Blue!</exclaim>\n), body end it "renders with inline layouts" do mock_app do layout { %(xml.layout { xml << yield }) } get('/') { builder %(xml.em 'Hello World') } end get '/' assert ok? assert_equal "<layout>\n<em>Hello World</em>\n</layout>\n", body end it "renders with file layouts" do builder_app do builder %(xml.em 'Hello World'), :layout => :layout2 end assert ok? assert_equal "<layout>\n<em>Hello World</em>\n</layout>\n", body end it "raises error if template not found" do mock_app do get('/') { builder :no_such_template } end assert_raises(Errno::ENOENT) { get('/') } end end rescue LoadError warn "#{$!}: skipping builder tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/haml_test.rb
test/haml_test.rb
require_relative 'test_helper' begin require 'haml' class HAMLTest < Minitest::Test def haml_app(&block) mock_app do set :views, __dir__ + '/views' get('/', &block) end get '/' end it 'renders inline HAML strings' do haml_app { haml '%h1 Hiya' } assert ok? assert_equal "<h1>Hiya</h1>\n", body end it 'renders .haml files in views path' do haml_app { haml :hello } assert ok? assert_equal "<h1>Hello From Haml</h1>\n", body end it "renders with inline layouts" do mock_app do layout { %q(%h1!= 'THIS. IS. ' + yield.upcase) } get('/') { haml '%em Sparta' } end get '/' assert ok? assert_equal "<h1>THIS. IS. <EM>SPARTA</EM>\n</h1>\n", body end it "renders with file layouts" do haml_app { haml 'Hello World', :layout => :layout2 } assert ok? assert_equal "<h1>HAML Layout!</h1>\n<p>Hello World\n</p>\n", body end it "raises error if template not found" do mock_app { get('/') { haml :no_such_template } } assert_raises(Errno::ENOENT) { get('/') } end it "passes HAML options to the Haml engine" do mock_app { get('/') { haml "!!!\n%h1 Hello World", :format => :html5 } } get '/' assert ok? assert_equal "<!DOCTYPE html>\n<h1>Hello World</h1>\n", body end it "passes default HAML options to the Haml engine" do mock_app do set :haml, {:format => :html5} get('/') { haml "!!!\n%h1 Hello World" } end get '/' assert ok? assert_equal "<!DOCTYPE html>\n<h1>Hello World</h1>\n", body end it "merges the default HAML options with the overrides and passes them to the Haml engine" do quote_char = Haml::VERSION >= "7.0.0" ? "\"" : "'" mock_app do set :haml, {:format => :html5} get('/') { haml "!!!\n%h1{:class => :header} Hello World" } get('/html4') { haml "!!!\n%h1{:class => 'header'} Hello World", :format => :html4 } end get '/' assert ok? assert_equal "<!DOCTYPE html>\n<h1 class=#{quote_char}header#{quote_char}>Hello World</h1>\n", body get '/html4' assert ok? assert_match(/^<!DOCTYPE html PUBLIC (.*) HTML 4.01/, body) end it "is possible to pass locals" do haml_app { haml "= foo", :locals => { :foo => 'bar' }} assert_equal "bar\n", body end it "can render truly nested layouts by accepting a layout and a block with the contents" do mock_app do template(:main_outer_layout) { "%h1 Title\n!= yield" } template(:an_inner_layout) { "%h2 Subtitle\n!= yield" } template(:a_page) { "%p Contents." } get('/') do haml :main_outer_layout, :layout => false do haml :an_inner_layout do haml :a_page end end end end get '/' assert ok? assert_body "<h1>Title</h1>\n<h2>Subtitle</h2>\n<p>Contents.</p>\n" end end rescue LoadError warn "#{$!}: skipping haml tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/readme_test.rb
test/readme_test.rb
require_relative 'test_helper' # Tests to check if all the README examples work. class ReadmeTest < Minitest::Test example do mock_app { get('/') { 'Hello world!' } } get '/' assert_body 'Hello world!' end section "Routes" do example do mock_app do get('/') { ".. show something .." } post('/') { ".. create something .." } put('/') { ".. replace something .." } patch('/') { ".. modify something .." } delete('/') { ".. annihilate something .." } options('/') { ".. appease something .." } link('/') { ".. affiliate something .." } unlink('/') { ".. separate something .." } end get '/' assert_body '.. show something ..' post '/' assert_body '.. create something ..' put '/' assert_body '.. replace something ..' patch '/' assert_body '.. modify something ..' delete '/' assert_body '.. annihilate something ..' options '/' assert_body '.. appease something ..' link '/' assert_body '.. affiliate something ..' unlink '/' assert_body '.. separate something ..' end example do mock_app do get('/hello/:name') do # matches "GET /hello/foo" and "GET /hello/bar" # params[:name] is 'foo' or 'bar' "Hello #{params[:name]}!" end end get '/hello/foo' assert_body 'Hello foo!' get '/hello/bar' assert_body 'Hello bar!' end example do mock_app { get('/hello/:name') { |n| "Hello #{n}!" } } get '/hello/foo' assert_body 'Hello foo!' get '/hello/bar' assert_body 'Hello bar!' end example do mock_app do get('/say/*/to/*') do # matches /say/hello/to/world params[:splat].inspect # => ["hello", "world"] end get('/download/*.*') do # matches /download/path/to/file.xml params[:splat].inspect # => ["path/to/file", "xml"] end end get "/say/hello/to/world" assert_body '["hello", "world"]' get "/download/path/to/file.xml" assert_body '["path/to/file", "xml"]' end example do mock_app do get(%r{/hello/([\w]+)}) { "Hello, #{params[:captures].first}!" } end get '/hello/foo' assert_body 'Hello, foo!' get '/hello/bar' assert_body 'Hello, bar!' end example do mock_app do get( %r{/hello/([\w]+)}) { |c| "Hello, #{c}!" } end get '/hello/foo' assert_body 'Hello, foo!' get '/hello/bar' assert_body 'Hello, bar!' end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/compile_test.rb
test/compile_test.rb
require_relative 'test_helper' class CompileTest < Minitest::Test def self.parses pattern, example, expected_params, mtype = :sinatra, mopts = {} it "parses #{example} with #{pattern} into params #{expected_params}" do compiled = mock_app { set :mustermann_opts, :type => mtype }.send(:compile, pattern, mopts) params = compiled.params(example) fail %Q{"#{example}" does not parse on pattern "#{pattern}".} unless params assert_equal expected_params, params, "Pattern #{pattern} does not match path #{example}." end end def self.fails pattern, example, mtype = :sinatra, mopts = {} it "does not parse #{example} with #{pattern}" do compiled = mock_app { set :mustermann_opts, :type => mtype }.send(:compile, pattern, mopts) match = compiled.match(example) fail %Q{"#{pattern}" does parse "#{example}" but it should fail} if match end end def self.raises pattern, mtype = :sinatra, mopts = {} it "does not compile #{pattern}" do assert_raises(Mustermann::CompileError, %Q{Pattern "#{pattern}" compiles but it should not}) do mock_app { set :mustermann_opts, :type => mtype }.send(:compile, pattern, mopts) end end end parses "/", "/", {} parses "/foo", "/foo", {} parses "/:foo", "/foo", "foo" => "foo" parses "/:foo", "/foo.bar", "foo" => "foo.bar" parses "/:foo", "/foo%2Fbar", "foo" => "foo/bar" parses "/:foo", "/%0Afoo", "foo" => "\nfoo" fails "/:foo", "/foo?" fails "/:foo", "/foo/bar" fails "/:foo", "/" fails "/:foo", "/foo/" parses "/föö", "/f%C3%B6%C3%B6", {} parses "/:foo/:bar", "/foo/bar", "foo" => "foo", "bar" => "bar" parses "/hello/:person", "/hello/Frank", "person" => "Frank" parses "/?:foo?/?:bar?", "/hello/world", "foo" => "hello", "bar" => "world" parses "/?:foo?/?:bar?", "/hello", "foo" => "hello", "bar" => nil parses "/?:foo?/?:bar?", "/", "foo" => nil, "bar" => nil parses "/?:foo?/?:bar?", "", "foo" => nil, "bar" => nil parses "/*", "/", "splat" => [""] parses "/*", "/foo", "splat" => ["foo"] parses "/*", "/foo/bar", "splat" => ["foo/bar"] parses "/:foo/*", "/foo/bar/baz", "foo" => "foo", "splat" => ["bar/baz"] parses "/:foo/:bar", "/user@example.com/name", "foo" => "user@example.com", "bar" => "name" parses "/test$/", "/test$/", {} parses "/te+st/", "/te+st/", {} fails "/te+st/", "/test/" fails "/te+st/", "/teeest/" parses "/test(bar)/", "/testbar/", {} parses "/path with spaces", "/path%20with%20spaces", {} parses "/path with spaces", "/path%2Bwith%2Bspaces", {} parses "/path with spaces", "/path+with+spaces", {} parses "/foo&bar", "/foo&bar", {} parses "/:foo/*", "/hello%20world/how%20are%20you", "foo" => "hello world", "splat" => ["how are you"] parses "/*/foo/*/*", "/bar/foo/bling/baz/boom", "splat" => ["bar", "bling", "baz/boom"] parses "/*/foo/*/*rest", "/bar/foo/bling/baz/boom", "splat" => ["bar", "bling"], "rest" => "baz/boom" fails "/*/foo/*/*", "/bar/foo/baz" parses "/test.bar", "/test.bar", {} fails "/test.bar", "/test0bar" parses "/:file.:ext", "/pony.jpg", "file" => "pony", "ext" => "jpg" parses "/:file.:ext", "/pony%2Ejpg", "file" => "pony", "ext" => "jpg" fails "/:file.:ext", "/.jpg" parses "/:name.?:format?", "/foo", "name" => "foo", "format" => nil parses "/:name.?:format?", "/foo.bar", "name" => "foo", "format" => "bar" parses "/:name.?:format?", "/foo%2Ebar", "name" => "foo", "format" => "bar" parses "/:user@?:host?", "/foo@bar", "user" => "foo", "host" => "bar" parses "/:user@?:host?", "/foo.foo@bar", "user" => "foo.foo", "host" => "bar" parses "/:user@?:host?", "/foo@bar.bar", "user" => "foo", "host" => "bar.bar" # From https://gist.github.com/2154980#gistcomment-169469. # parses "/:name(.:format)?", "/foo", "name" => "foo", "format" => nil parses "/:name(.:format)?", "/foo.bar", "name" => "foo", "format" => "bar" parses "/:name(.:format)?", "/foo.", "name" => "foo.", "format" => nil parses "/:id/test.bar", "/3/test.bar", {"id" => "3"} parses "/:id/test.bar", "/2/test.bar", {"id" => "2"} parses "/:id/test.bar", "/2E/test.bar", {"id" => "2E"} parses "/:id/test.bar", "/2e/test.bar", {"id" => "2e"} parses "/:id/test.bar", "/%2E/test.bar", {"id" => "."} parses "/{id}/test.bar", "/%2E/test.bar", {"id" => "."} parses '/10/:id', '/10/test', "id" => "test" parses '/10/:id', '/10/te.st', "id" => "te.st" parses '/10.1/:id', '/10.1/test', "id" => "test" parses '/10.1/:id', '/10.1/te.st', "id" => "te.st" parses '/:foo/:id', '/10.1/te.st', "foo" => "10.1", "id" => "te.st" parses '/:foo/:id', '/10.1.2/te.st', "foo" => "10.1.2", "id" => "te.st" parses '/:foo.:bar/:id', '/10.1/te.st', "foo" => "10", "bar" => "1", "id" => "te.st" parses '/:a/:b.?:c?', '/a/b', "a" => "a", "b" => "b", "c" => nil parses '/:a/:b.?:c?', '/a/b.c', "a" => "a", "b" => "b", "c" => "c" parses '/:a/:b.?:c?', '/a.b/c', "a" => "a.b", "b" => "c", "c" => nil parses '/:a/:b.?:c?', '/a.b/c.d', "a" => "a.b", "b" => "c", "c" => "d" fails '/:a/:b.?:c?', '/a.b/c.d/e' parses "/:file.:ext", "/pony%2ejpg", "file" => "pony", "ext" => "jpg" parses "/:file.:ext", "/pony%E6%AD%A3%2Ejpg", "file" => "pony正", "ext" => "jpg" parses "/:file.:ext", "/pony%e6%ad%a3%2ejpg", "file" => "pony正", "ext" => "jpg" parses "/:file.:ext", "/pony正%2Ejpg", "file" => "pony正", "ext" => "jpg" parses "/:file.:ext", "/pony正%2ejpg", "file" => "pony正", "ext" => "jpg" parses "/:file.:ext", "/pony正..jpg", "file" => "pony正.", "ext" => "jpg" parses "/:name.:format", "/file.tar.gz", "name" => "file.tar", "format" => "gz" parses "/:name.:format1.:format2", "/file.tar.gz", "name" => "file", "format1" => "tar", "format2" => "gz" parses "/:name.:format1.:format2", "/file.temp.tar.gz", "name" => "file.temp", "format1" => "tar", "format2" => "gz" # From issue #688. # parses "/articles/10.1103/:doi", "/articles/10.1103/PhysRevLett.110.026401", "doi" => "PhysRevLett.110.026401" # Mustermann anchoring fails "/bar", "/foo/bar", :regexp raises "^/foo/bar$", :regexp parses "^/foo/bar$", "/foo/bar", {}, :regexp, :check_anchors => false end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/helpers_test.rb
test/helpers_test.rb
require_relative 'test_helper' require 'date' require 'json' class HelpersTest < Minitest::Test def test_default assert true end def status_app(code, &block) code += 2 if [204, 304].include? code block ||= proc { } mock_app do get('/') do status code instance_eval(&block).inspect end end get '/' end describe 'status' do it 'sets the response status code' do status_app 207 assert_equal 207, response.status end end describe 'bad_request?' do it 'is true for status == 400' do status_app(400) { bad_request? } assert_body 'true' end it 'is false for status gt 400' do status_app(401) { bad_request? } assert_body 'false' end it 'is false for status lt 400' do status_app(399) { bad_request? } assert_body 'false' end end describe 'not_found?' do it 'is true for status == 404' do status_app(404) { not_found? } assert_body 'true' end it 'is false for status gt 404' do status_app(405) { not_found? } assert_body 'false' end it 'is false for status lt 404' do status_app(403) { not_found? } assert_body 'false' end end describe 'informational?' do it 'is true for 1xx status' do status_app(100 + rand(100)) { informational? } assert_body 'true' end it 'is false for status > 199' do status_app(200 + rand(400)) { informational? } assert_body 'false' end end describe 'success?' do it 'is true for 2xx status' do status_app(200 + rand(100)) { success? } assert_body 'true' end it 'is false for status < 200' do status_app(100 + rand(100)) { success? } assert_body 'false' end it 'is false for status > 299' do status_app(300 + rand(300)) { success? } assert_body 'false' end end describe 'redirect?' do it 'is true for 3xx status' do status_app(300 + rand(100)) { redirect? } assert_body 'true' end it 'is false for status < 300' do status_app(200 + rand(100)) { redirect? } assert_body 'false' end it 'is false for status > 399' do status_app(400 + rand(200)) { redirect? } assert_body 'false' end end describe 'client_error?' do it 'is true for 4xx status' do status_app(400 + rand(100)) { client_error? } assert_body 'true' end it 'is false for status < 400' do status_app(200 + rand(200)) { client_error? } assert_body 'false' end it 'is false for status > 499' do status_app(500 + rand(100)) { client_error? } assert_body 'false' end end describe 'server_error?' do it 'is true for 5xx status' do status_app(500 + rand(100)) { server_error? } assert_body 'true' end it 'is false for status < 500' do status_app(200 + rand(300)) { server_error? } assert_body 'false' end end describe 'body' do it 'takes a block for deferred body generation' do mock_app do get('/') { body { 'Hello World' } } end get '/' assert_equal 'Hello World', body end it 'takes a String, Array, or other object responding to #each' do mock_app { get('/') { body 'Hello World' } } get '/' assert_equal 'Hello World', body end it 'can be used with other objects' do mock_app do get '/' do body :hello => 'from json' end after do if Hash === response.body body response.body[:hello] end end end get '/' assert_body 'from json' end it 'can be set in after filter' do mock_app do get('/') { body 'route' } after { body 'filter' } end get '/' assert_body 'filter' end end describe 'redirect' do it 'uses a 302 when only a path is given' do mock_app do get('/') do redirect '/foo' fail 'redirect should halt' end end get '/' assert_equal 302, status assert_equal '', body assert_equal 'http://example.org/foo', response['Location'] end it 'uses the code given when specified' do mock_app do get('/') do redirect '/foo', 301 fail 'redirect should halt' end end get '/' assert_equal 301, status assert_equal '', body assert_equal 'http://example.org/foo', response['Location'] end it 'redirects back to request.referer when passed back' do mock_app { get('/try_redirect') { redirect back } } request = Rack::MockRequest.new(@app) response = request.get('/try_redirect', 'HTTP_REFERER' => '/foo') assert_equal 302, response.status assert_equal 'http://example.org/foo', response['Location'] end it 'redirects using a non-standard HTTP port' do mock_app { get('/') { redirect '/foo' } } request = Rack::MockRequest.new(@app) response = request.get('/', 'SERVER_PORT' => '81') assert_equal 'http://example.org:81/foo', response['Location'] end it 'redirects using a non-standard HTTPS port' do mock_app { get('/') { redirect '/foo' } } request = Rack::MockRequest.new(@app) response = request.get('/', 'SERVER_PORT' => '444') assert_equal 'http://example.org:444/foo', response['Location'] end it 'uses 303 for post requests if request is HTTP 1.1' do mock_app { post('/') { redirect '/'} } post('/', {}, 'SERVER_PROTOCOL' => 'HTTP/1.1') assert_equal 303, status assert_equal '', body assert_equal 'http://example.org/', response['Location'] end it 'uses 302 for post requests if request is HTTP 1.0' do mock_app { post('/') { redirect '/'} } post('/', {}, 'SERVER_PROTOCOL' => 'HTTP/1.0') assert_equal 302, status assert_equal '', body assert_equal 'http://example.org/', response['Location'] end it 'works behind a reverse proxy' do mock_app { get('/') { redirect '/foo' } } request = Rack::MockRequest.new(@app) response = request.get('/', 'HTTP_X_FORWARDED_HOST' => 'example.com', 'SERVER_PORT' => '8080') assert_equal 'http://example.com/foo', response['Location'] end it 'accepts absolute URIs' do mock_app do get('/') do redirect 'http://google.com' fail 'redirect should halt' end end get '/' assert_equal 302, status assert_equal '', body assert_equal 'http://google.com', response['Location'] end it 'accepts absolute URIs with a different schema' do mock_app do get('/') do redirect 'mailto:jsmith@example.com' fail 'redirect should halt' end end get '/' assert_equal 302, status assert_equal '', body assert_equal 'mailto:jsmith@example.com', response['Location'] end it 'accepts a URI object instead of a String' do mock_app do get('/') { redirect URI.parse('http://sinatrarb.com') } end get '/' assert_equal 302, status assert_equal '', body assert_equal 'http://sinatrarb.com', response['Location'] end end describe 'error' do it 'sets a status code and halts' do mock_app do get('/') do error 501 fail 'error should halt' end end get '/' assert_equal 501, status assert_equal '', body end it 'takes an optional body' do mock_app do get('/') do error 501, 'FAIL' fail 'error should halt' end end get '/' assert_equal 501, status assert_equal 'FAIL', body end it 'should not invoke error handler when setting status inside an error handler' do mock_app do disable :raise_errors not_found do body "not_found handler" status 404 end error do body "error handler" status 404 end get '/' do raise end end get '/' assert_equal 404, status assert_equal 'error handler', body end it 'should not reset the content-type to html for error handlers' do mock_app do disable :raise_errors before { content_type "application/json" } not_found { JSON.dump("error" => "Not Found") } end get '/' assert_equal 404, status assert_equal 'application/json', response.content_type end it 'should not invoke error handler when halting with 500 inside an error handler' do mock_app do disable :raise_errors not_found do body "not_found handler" halt 404 end error do body "error handler" halt 404 end get '/' do raise end end get '/' assert_equal 404, status assert_equal 'error handler', body end it 'should not invoke not_found handler when halting with 404 inside a not found handler' do mock_app do disable :raise_errors not_found do body "not_found handler" halt 500 end error do body "error handler" halt 500 end end get '/' assert_equal 500, status assert_equal 'not_found handler', body end it 'uses a 500 status code when first argument is a body' do mock_app do get('/') do error 'FAIL' fail 'error should halt' end end get '/' assert_equal 500, status assert_equal 'FAIL', body end end describe 'not_found' do it 'halts with a 404 status' do mock_app do get('/') do not_found fail 'not_found should halt' end end get '/' assert_equal 404, status assert_equal '', body end it 'does not set a X-Cascade header' do mock_app do get('/') do not_found fail 'not_found should halt' end end get '/' assert_equal 404, status assert_nil response.headers['X-Cascade'] end end describe 'headers' do it 'sets headers on the response object when given a Hash' do mock_app do get('/') do headers 'X-Foo' => 'bar', 'X-Baz' => 'bling' 'kthx' end end get '/' assert ok? assert_equal 'bar', response['X-Foo'] assert_equal 'bling', response['X-Baz'] assert_equal 'kthx', body end it 'returns the response headers hash when no hash provided' do mock_app do get('/') do headers['X-Foo'] = 'bar' 'kthx' end end get '/' assert ok? assert_equal 'bar', response['X-Foo'] end end describe 'session' do it 'uses the existing rack.session' do mock_app do get('/') do session[:foo] end end get('/', {}, { 'rack.session' => { :foo => 'bar' } }) assert_equal 'bar', body end it 'creates a new session when none provided' do mock_app do enable :sessions get('/') do assert session[:foo].nil? session[:foo] = 'bar' redirect '/hi' end get('/hi') do "hi #{session[:foo]}" end end get '/' follow_redirect! assert_equal 'hi bar', body end it 'inserts session middleware' do mock_app do enable :sessions get('/') do assert env['rack.session'] assert env['rack.session.options'] 'ok' end end get '/' assert_body 'ok' end it 'sets a default session secret' do mock_app do enable :sessions get('/') do secret = env['rack.session.options'][:secret] assert secret assert_equal secret, settings.session_secret 'ok' end end get '/' assert_body 'ok' end it 'allows disabling session secret' do mock_app do enable :sessions disable :session_secret get('/') do assert !env['rack.session.options'].include?(:session_secret) 'ok' end end # Silence warnings since Rack::Session::Cookie complains about the non-present session secret silence_warnings do get '/' end assert_body 'ok' end it 'accepts an options hash' do mock_app do set :sessions, :foo => :bar get('/') do assert_equal env['rack.session.options'][:foo], :bar 'ok' end end get '/' assert_body 'ok' end end describe 'mime_type' do include Sinatra::Helpers it "looks up mime types in Rack's MIME registry" do Rack::Mime::MIME_TYPES['.foo'] = 'application/foo' assert_equal 'application/foo', mime_type('foo') assert_equal 'application/foo', mime_type('.foo') assert_equal 'application/foo', mime_type(:foo) end it 'returns nil when given nil' do assert mime_type(nil).nil? end it 'returns nil when media type not registered' do assert mime_type(:bizzle).nil? end it 'returns the argument when given a media type string' do assert_equal 'text/plain', mime_type('text/plain') end it 'turns AcceptEntry into String' do type = mime_type(Sinatra::Request::AcceptEntry.new('text/plain')) assert_equal String, type.class assert_equal 'text/plain', type end end test 'Base.mime_type registers mime type' do mock_app do mime_type :foo, 'application/foo' get('/') do "foo is #{mime_type(:foo)}" end end get '/' assert_equal 'foo is application/foo', body end describe 'content_type' do it 'sets the Content-Type header' do mock_app do get('/') do content_type 'text/plain' 'Hello World' end end get '/' assert_equal 'text/plain;charset=utf-8', response['Content-Type'] assert_equal 'Hello World', body end it 'takes media type parameters (like charset=)' do mock_app do get('/') do content_type 'text/html', :charset => 'latin1' "<h1>Hello, World</h1>" end end get '/' assert ok? assert_equal 'text/html;charset=latin1', response['Content-Type'] assert_equal "<h1>Hello, World</h1>", body end it "looks up symbols in Rack's mime types dictionary" do Rack::Mime::MIME_TYPES['.foo'] = 'application/foo' mock_app do get('/foo.xml') do content_type :foo "I AM FOO" end end get '/foo.xml' assert ok? assert_equal 'application/foo', response['Content-Type'] assert_equal 'I AM FOO', body end it 'fails when no mime type is registered for the argument provided' do mock_app do get('/foo.xml') do content_type :bizzle "I AM FOO" end end assert_raises(RuntimeError) { get '/foo.xml' } end it 'only sets default charset for specific mime types' do tests_ran = false mock_app do mime_type :foo, 'text/foo' mime_type :bar, 'application/bar' mime_type :baz, 'application/baz' add_charset << mime_type(:baz) get('/') do assert_equal content_type(:txt), 'text/plain;charset=utf-8' assert_equal content_type(:css), 'text/css;charset=utf-8' assert_equal content_type(:html), 'text/html;charset=utf-8' assert_equal content_type(:foo), 'text/foo;charset=utf-8' assert_equal content_type(:xml), 'application/xml;charset=utf-8' assert_equal content_type(:xhtml), 'application/xhtml+xml;charset=utf-8' assert_equal content_type(:json), 'application/json' assert_equal content_type(:bar), 'application/bar' assert_equal content_type(:png), 'image/png' assert_equal content_type(:baz), 'application/baz;charset=utf-8' # Changed to "text/javascript" in Rack >3.0 # https://github.com/sinatra/sinatra/pull/1857#issuecomment-1445062212 assert_match %r{^application|text/javascript;charset=utf-8$}, content_type(:js) tests_ran = true "done" end end get '/' assert tests_ran end it 'handles already present params' do mock_app do get('/') do content_type 'foo/bar;level=1', :charset => 'utf-8' 'ok' end end get '/' assert_equal 'foo/bar;level=1;charset=utf-8', response['Content-Type'] end it 'handles multiple params' do mock_app do get('/') do content_type 'foo/bar;level=1', :charset => 'utf-8', :version => '1.0' 'ok' end end get '/' assert_equal 'foo/bar;level=1;charset=utf-8;version=1.0', response['Content-Type'] end it 'does not add charset if present' do mock_app do get('/') do content_type 'text/plain;charset=utf-16' 'ok' end end get '/' assert_equal 'text/plain;charset=utf-16', response['Content-Type'] end it 'properly encodes parameters with delimiter characters' do mock_app do before '/comma' do content_type 'image/png', :comment => 'Hello, world!' end before '/semicolon' do content_type 'image/png', :comment => 'semi;colon' end before '/quote' do content_type 'image/png', :comment => '"Whatever."' end get('*') { 'ok' } end get '/comma' assert_equal 'image/png;comment="Hello, world!"', response['Content-Type'] get '/semicolon' assert_equal 'image/png;comment="semi;colon"', response['Content-Type'] get '/quote' assert_equal 'image/png;comment="\"Whatever.\""', response['Content-Type'] end end describe 'attachment' do def attachment_app(filename=nil) mock_app do get('/attachment') do attachment filename response.write("<sinatra></sinatra>") end end end it 'sets the Content-Type response header' do attachment_app('test.xml') get '/attachment' assert_equal 'application/xml;charset=utf-8', response['Content-Type'] assert_equal '<sinatra></sinatra>', body end it 'sets the Content-Type response header without extname' do attachment_app('test') get '/attachment' assert_equal 'text/html;charset=utf-8', response['Content-Type'] assert_equal '<sinatra></sinatra>', body end it 'sets the Content-Type response header with extname' do mock_app do get('/attachment') do content_type :atom attachment 'test.xml' response.write("<sinatra></sinatra>") end end get '/attachment' assert_equal 'application/atom+xml', response['Content-Type'] assert_equal '<sinatra></sinatra>', body end it 'escapes filename in the Content-Disposition header according to the multipart form data spec in WHATWG living standard' do mock_app do get('/attachment') do attachment "test.xml\";\r\next=.txt" response.write("<sinatra></sinatra>") end end get '/attachment' assert_equal 'attachment; filename="test.xml%22;%0D%0Aext=.txt"', response['Content-Disposition'] assert_equal '<sinatra></sinatra>', body end end describe 'send_file' do setup do @file = __dir__ + '/file.txt' File.open(@file, 'wb') { |io| io.write('Hello World') } end def teardown File.unlink @file @file = nil end def send_file_app(opts={}) path = @file mock_app { get '/file.txt' do send_file path, opts end } end it "sends the contents of the file" do send_file_app get '/file.txt' assert ok? assert_equal 'Hello World', body end it 'sets the Content-Type response header if a mime-type can be located' do send_file_app get '/file.txt' assert_equal 'text/plain;charset=utf-8', response['Content-Type'] end it 'sets the Content-Type response header if type option is set to a file extension' do send_file_app :type => 'html' get '/file.txt' assert_equal 'text/html;charset=utf-8', response['Content-Type'] end it 'sets the Content-Type response header if type option is set to a mime type' do send_file_app :type => 'application/octet-stream' get '/file.txt' assert_equal 'application/octet-stream', response['Content-Type'] end it 'sets the Content-Length response header' do send_file_app get '/file.txt' assert_equal 'Hello World'.length.to_s, response['Content-Length'] end it 'sets the Last-Modified response header' do send_file_app get '/file.txt' assert_equal File.mtime(@file).httpdate, response['Last-Modified'] end it 'allows passing in a different Last-Modified response header with :last_modified' do time = Time.now send_file_app :last_modified => time get '/file.txt' assert_equal time.httpdate, response['Last-Modified'] end it "returns a 404 when not found" do mock_app { get('/') { send_file 'this-file-does-not-exist.txt' } } get '/' assert not_found? end it "does not set the Content-Disposition header by default" do send_file_app get '/file.txt' assert_nil response['Content-Disposition'] end it "sets the Content-Disposition header when :disposition set to 'attachment'" do send_file_app :disposition => 'attachment' get '/file.txt' assert_equal 'attachment; filename="file.txt"', response['Content-Disposition'] end it "does not set add a file name if filename is false" do send_file_app :disposition => 'inline', :filename => false get '/file.txt' assert_equal 'inline', response['Content-Disposition'] end it "sets the Content-Disposition header when :disposition set to 'inline'" do send_file_app :disposition => 'inline' get '/file.txt' assert_equal 'inline; filename="file.txt"', response['Content-Disposition'] end it "does not raise an error when :disposition set to a frozen string" do send_file_app :disposition => 'inline'.freeze get '/file.txt' assert_equal 'inline; filename="file.txt"', response['Content-Disposition'] end it "sets the Content-Disposition header when :filename provided" do send_file_app :filename => 'foo.txt' get '/file.txt' assert_equal 'attachment; filename="foo.txt"', response['Content-Disposition'] end it 'allows setting a custom status code' do send_file_app :status => 201 get '/file.txt' assert_status 201 end it "is able to send files with unknown mime type" do @file = __dir__ + '/file.foobar' File.open(@file, 'wb') { |io| io.write('Hello World') } send_file_app get '/file.txt' assert_equal 'application/octet-stream', response['Content-Type'] end it "does not override Content-Type if already set and no explicit type is given" do path = @file mock_app do get('/') do content_type :png send_file path end end get '/' assert_equal 'image/png', response['Content-Type'] end it "does override Content-Type even if already set, if explicit type is given" do path = @file mock_app do get('/') do content_type :png send_file path, :type => :gif end end get '/' assert_equal 'image/gif', response['Content-Type'] end it 'can have :status option as a string' do path = @file mock_app do post '/' do send_file path, :status => '422' end end post '/' assert_equal response.status, 422 end end describe 'cache_control' do setup do mock_app do get('/foo') do cache_control :public, :no_cache, :max_age => 60.0 'Hello World' end get('/bar') do cache_control :public, :no_cache 'Hello World' end end end it 'sets the Cache-Control header' do get '/foo' assert_equal ['public', 'no-cache', 'max-age=60'], response['Cache-Control'].split(', ') end it 'last argument does not have to be a hash' do get '/bar' assert_equal ['public', 'no-cache'], response['Cache-Control'].split(', ') end end describe 'expires' do setup do mock_app do get('/foo') do expires 60, :public, :no_cache 'Hello World' end get('/bar') { expires Time.now } get('/baz') { expires Time.at(0) } get('/bah') { expires Time.at(0), :max_age => 20 } get('/blah') do obj = Object.new def obj.method_missing(*a, &b) 60.send(*a, &b) end def obj.is_a?(thing) 60.is_a?(thing) end expires obj, :public, :no_cache 'Hello World' end get('/boom') { expires '9999' } end end it 'sets the Cache-Control header' do get '/foo' assert_equal ['public', 'no-cache', 'max-age=60'], response['Cache-Control'].split(', ') end it 'sets the Expires header' do get '/foo' refute_nil response['Expires'] end it 'allows passing Time.now objects' do get '/bar' refute_nil response['Expires'] end it 'allows passing Time.at objects' do get '/baz' assert_equal 'Thu, 01 Jan 1970 00:00:00 GMT', response['Expires'] end it 'allows max_age to be specified separately' do get '/bah' assert_equal 'Thu, 01 Jan 1970 00:00:00 GMT', response['Expires'] assert_equal ['max-age=20'], response['Cache-Control'].split(', ') end it 'accepts values pretending to be a Numeric (like ActiveSupport::Duration)' do get '/blah' assert_equal ['public', 'no-cache', 'max-age=60'], response['Cache-Control'].split(', ') end it 'fails when Time.parse raises an ArgumentError' do assert_raises(ArgumentError) { get '/boom' } end end describe 'last_modified' do it 'ignores nil' do mock_app { get('/') { last_modified nil; 200; } } get '/' assert ! response['Last-Modified'] end it 'does not change a status other than 200' do mock_app do get('/') do status 299 last_modified Time.at(0) 'ok' end end get('/', {}, 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2030 23:43:52 GMT') assert_status 299 assert_body 'ok' end [Time.now, DateTime.now, Date.today, Time.now.to_i, Struct.new(:to_time).new(Time.now) ].each do |last_modified_time| describe "with #{last_modified_time.class.name}" do setup do mock_app do get('/') do last_modified last_modified_time 'Boo!' end end wrapper = Object.new.extend Sinatra::Helpers @last_modified_time = wrapper.time_for last_modified_time end # fixes strange missing test error when running complete test suite. it("does not complain about missing tests") { } context "when there's no If-Modified-Since header" do it 'sets the Last-Modified header to a valid RFC 2616 date value' do get '/' assert_equal @last_modified_time.httpdate, response['Last-Modified'] end it 'conditional GET misses and returns a body' do get '/' assert_equal 200, status assert_equal 'Boo!', body end end context "when there's an invalid If-Modified-Since header" do it 'sets the Last-Modified header to a valid RFC 2616 date value' do get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => 'a really weird date' }) assert_equal @last_modified_time.httpdate, response['Last-Modified'] end it 'conditional GET misses and returns a body' do get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => 'a really weird date' }) assert_equal 200, status assert_equal 'Boo!', body end end context "when the resource has been modified since the If-Modified-Since header date" do it 'sets the Last-Modified header to a valid RFC 2616 date value' do get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => (@last_modified_time - 1).httpdate }) assert_equal @last_modified_time.httpdate, response['Last-Modified'] end it 'conditional GET misses and returns a body' do get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => (@last_modified_time - 1).httpdate }) assert_equal 200, status assert_equal 'Boo!', body end it 'does not rely on string comparison' do mock_app do get('/compare') do last_modified "Mon, 18 Oct 2010 20:57:11 GMT" "foo" end end get('/compare', {}, { 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2010 23:43:52 GMT' }) assert_equal 200, status assert_equal 'foo', body get('/compare', {}, { 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2030 23:43:52 GMT' }) assert_equal 304, status assert_equal '', body end end context "when the resource has been modified on the exact If-Modified-Since header date" do it 'sets the Last-Modified header to a valid RFC 2616 date value' do get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => @last_modified_time.httpdate }) assert_equal @last_modified_time.httpdate, response['Last-Modified'] end it 'conditional GET matches and halts' do get( '/', {}, { 'HTTP_IF_MODIFIED_SINCE' => @last_modified_time.httpdate }) assert_equal 304, status assert_equal '', body end end context "when the resource hasn't been modified since the If-Modified-Since header date" do it 'sets the Last-Modified header to a valid RFC 2616 date value' do get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => (@last_modified_time + 1).httpdate }) assert_equal @last_modified_time.httpdate, response['Last-Modified'] end it 'conditional GET matches and halts' do get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => (@last_modified_time + 1).httpdate }) assert_equal 304, status assert_equal '', body end end context "If-Unmodified-Since" do it 'results in 200 if resource has not been modified' do get('/', {}, { 'HTTP_IF_UNMODIFIED_SINCE' => 'Sun, 26 Sep 2030 23:43:52 GMT' }) assert_equal 200, status assert_equal 'Boo!', body end it 'results in 412 if resource has been modified' do get('/', {}, { 'HTTP_IF_UNMODIFIED_SINCE' => Time.at(0).httpdate }) assert_equal 412, status assert_equal '', body end end end end end describe 'etag' do context "safe requests" do it 'returns 200 for normal requests' do mock_app do get('/') do etag 'foo' 'ok' end end get '/' assert_status 200 assert_body 'ok' end context "If-None-Match" do it 'returns 304 when If-None-Match is *' do mock_app do get('/') do etag 'foo' 'ok' end end get('/', {}, 'HTTP_IF_NONE_MATCH' => '*') assert_status 304 assert_body '' end it 'returns 200 when If-None-Match is * for new resources' do mock_app do get('/') do etag 'foo', :new_resource => true 'ok' end end get('/', {}, 'HTTP_IF_NONE_MATCH' => '*')
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
true
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/liquid_test.rb
test/liquid_test.rb
require_relative 'test_helper' begin require 'liquid' class LiquidTest < Minitest::Test def liquid_app(&block) mock_app do set :views, __dir__ + '/views' get('/', &block) end get '/' end it 'renders inline liquid strings' do liquid_app { liquid '<h1>Hiya</h1>' } assert ok? assert_equal "<h1>Hiya</h1>", body end it 'renders .liquid files in views path' do liquid_app { liquid :hello } assert ok? assert_equal "<h1>Hello From Liquid</h1>\n", body end it "renders with inline layouts" do mock_app do layout { "<h1>THIS. IS. {{ yield }}</h1>" } get('/') { liquid '<EM>SPARTA</EM>' } end get '/' assert ok? assert_equal "<h1>THIS. IS. <EM>SPARTA</EM></h1>", body end it "renders with file layouts" do liquid_app { liquid 'Hello World', :layout => :layout2 } assert ok? assert_equal "<h1>Liquid Layout!</h1>\n<p>Hello World</p>\n", body end it "raises error if template not found" do mock_app { get('/') { liquid :no_such_template } } assert_raises(Errno::ENOENT) { get('/') } end it "allows passing locals" do liquid_app { liquid '{{ value }}', :locals => { :value => 'foo' } } assert ok? assert_equal 'foo', body end it "can render truly nested layouts by accepting a layout and a block with the contents" do mock_app do template(:main_outer_layout) { "<h1>Title</h1>\n{{ yield }}" } template(:an_inner_layout) { "<h2>Subtitle</h2>\n{{ yield }}" } template(:a_page) { "<p>Contents.</p>\n" } get('/') do liquid :main_outer_layout, :layout => false do liquid :an_inner_layout do liquid :a_page end end end end get '/' assert ok? assert_body "<h1>Title</h1>\n<h2>Subtitle</h2>\n<p>Contents.</p>\n" end end rescue LoadError warn "#{$!}: skipping liquid tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/sass_test.rb
test/sass_test.rb
require_relative 'test_helper' begin require 'sass-embedded' class SassTest < Minitest::Test def sass_app(options = {}, &block) mock_app do set :views, __dir__ + '/views' set options get('/', &block) end get '/' end it 'renders inline Sass strings' do sass_app { sass "#sass\n background-color: white\n" } assert ok? assert_equal "#sass {\n background-color: white;\n}", body end it 'defaults content type to css' do sass_app { sass "#sass\n background-color: white\n" } assert ok? assert_equal "text/css;charset=utf-8", response['Content-Type'] end it 'defaults allows setting content type per route' do sass_app do content_type :html sass "#sass\n background-color: white\n" end assert ok? assert_equal "text/html;charset=utf-8", response['Content-Type'] end it 'defaults allows setting content type globally' do sass_app(:sass => { :content_type => 'html' }) { sass "#sass\n background-color: white\n" } assert ok? assert_equal "text/html;charset=utf-8", response['Content-Type'] end it 'renders .sass files in views path' do sass_app { sass :hello } assert ok? assert_equal "#sass {\n background-color: white;\n}", body end it 'ignores the layout option' do sass_app { sass :hello, :layout => :layout2 } assert ok? assert_equal "#sass {\n background-color: white;\n}", body end it "raises error if template not found" do mock_app { get('/') { sass :no_such_template } } assert_raises(Errno::ENOENT) { get('/') } end it "passes SASS options to the Sass engine" do sass_app do sass( "#sass\n background-color: white\n color: black\n", :style => :compressed ) end assert ok? assert_equal("#sass{background-color:#fff;color:#000}", body) end it "passes default SASS options to the Sass engine" do mock_app do set :sass, {:style => :compressed} # default Sass style is :expanded get('/') { sass("#sass\n background-color: white\n color: black\n") } end get '/' assert ok? assert_equal "#sass{background-color:#fff;color:#000}", body end end rescue LoadError warn "#{$!}: skipping sass tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/yajl_test.rb
test/yajl_test.rb
require_relative 'test_helper' begin require 'yajl' class YajlTest < Minitest::Test def yajl_app(&block) mock_app do set :views, __dir__ + '/views' get('/', &block) end get '/' end it 'renders inline Yajl strings' do yajl_app { yajl('json = { :foo => "bar" }') } assert ok? assert_body '{"foo":"bar"}' end it 'renders .yajl files in views path' do yajl_app { yajl(:hello) } assert ok? assert_body '{"yajl":"hello"}' end it 'raises error if template not found' do mock_app { get('/') { yajl(:no_such_template) } } assert_raises(Errno::ENOENT) { get('/') } end it 'accepts a :locals option' do yajl_app do locals = { :object => { :foo => 'bar' } } yajl 'json = object', :locals => locals end assert ok? assert_body '{"foo":"bar"}' end it 'accepts a :scope option' do yajl_app do scope = { :object => { :foo => 'bar' } } yajl 'json = self[:object]', :scope => scope end assert ok? assert_body '{"foo":"bar"}' end it 'decorates the json with a callback' do yajl_app do yajl( 'json = { :foo => "bar" }', { :callback => 'baz' } ) end assert ok? assert_body 'baz({"foo":"bar"});' end it 'decorates the json with a variable' do yajl_app do yajl( 'json = { :foo => "bar" }', { :variable => 'qux' } ) end assert ok? assert_body 'var qux = {"foo":"bar"};' end it 'decorates the json with a callback and a variable' do yajl_app do yajl( 'json = { :foo => "bar" }', { :callback => 'baz', :variable => 'qux' } ) end assert ok? assert_body 'var qux = {"foo":"bar"}; baz(qux);' end end rescue LoadError warn "#{$!}: skipping yajl tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/markdown_test.rb
test/markdown_test.rb
require_relative 'test_helper' MarkdownTest = proc do def markdown_app(&block) mock_app do set :views, __dir__ + '/views' get('/', &block) end get '/' end def setup Tilt.prefer engine, 'markdown', 'mkd', 'md' super end # commonmarker is not installed on all platforms (e.g. jruby) def commonmarker_v1_or_higher? defined?(CommonMarkerTest) && self.class == CommonMarkerTest && defined?(::Commonmarker) end it 'uses the correct engine' do assert_equal engine, Tilt[:md] assert_equal engine, Tilt[:mkd] assert_equal engine, Tilt[:markdown] end it 'renders inline markdown strings' do markdown_app { markdown '# Hiya' } assert ok? if commonmarker_v1_or_higher? assert_equal "<h1><a href=\"#hiya\" aria-hidden=\"true\" class=\"anchor\" id=\"hiya\"></a>Hiya</h1>\n", body else assert_like "<h1>Hiya</h1>\n", body end end it 'renders .markdown files in views path' do markdown_app { markdown :hello } assert ok? if commonmarker_v1_or_higher? assert_equal "<h1><a href=\"#hello-from-markdown\" aria-hidden=\"true\" " \ "class=\"anchor\" id=\"hello-from-markdown\"></a>Hello From Markdown</h1>\n", body else assert_like "<h1>Hello From Markdown</h1>", body end end it "raises error if template not found" do mock_app { get('/') { markdown :no_such_template } } assert_raises(Errno::ENOENT) { get('/') } end it "renders with inline layouts" do mock_app do layout { 'THIS. IS. #{yield.upcase}!' } get('/') { markdown 'Sparta', :layout_engine => :str } end get '/' assert ok? assert_like 'THIS. IS. <P>SPARTA</P>!', body end it "renders with file layouts" do markdown_app { markdown 'Hello World', :layout => :layout2, :layout_engine => :erb } assert ok? assert_body "ERB Layout!\n<p>Hello World</p>" end it "can be used in a nested fashion for partials and whatnot" do mock_app do template(:inner) { "hi" } template(:outer) { "<outer><%= markdown :inner %></outer>" } get('/') { erb :outer } end get '/' assert ok? assert_like '<outer><p>hi</p></outer>', body end end [ "Tilt::PandocTemplate", "Tilt::CommonMarkerTemplate", "Tilt::KramdownTemplate", "Tilt::RedcarpetTemplate", "Tilt::RDiscountTemplate" ].each do |template_name| begin template = Object.const_get(template_name) klass = Class.new(Minitest::Test) { define_method(:engine) { template } } klass.class_eval(&MarkdownTest) name = template_name.split('::').last.sub(/Template$/, 'Test') Object.const_set name, klass rescue LoadError, NameError warn "#{$!}: skipping markdown tests with #{template_name}" end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/integration_start_helper.rb
test/integration_start_helper.rb
require "childprocess" require "expect" require "minitest/autorun" module IntegrationStartHelper def command_for(app_file) [ "ruby", app_file, "-p", "0", # any free port "-s", "puma", ] end def with_process(command:, env: {}, debug: false) process = ChildProcess.build(*command) process.leader = true # ensure entire process tree dies process.environment.merge!(env) read_io, write_io = IO.pipe process.io.stdout = write_io process.io.stderr = write_io process.start # Close parent's copy of the write end of the pipe so when the (forked) child # process closes its write end of the pipe the parent receives EOF when # attempting to read from it. If the parent leaves its write end open, it # will not detect EOF. write_io.close echo_output(read_io) if debug || debug_all? yield process, read_io ensure read_io.close process.stop end def echo_output(read_io) Thread.new do begin loop { print read_io.readpartial(8192) } rescue EOFError end end end def debug_all? ENV.key?("DEBUG_START_PROCESS") end def wait_timeout case RUBY_ENGINE when "jruby", "truffleruby" # takes some time to start the JVM 10.0 else 3.0 end end def wait_for_output(read_io, matcher, timeout = wait_timeout) return true if read_io.expect(matcher, timeout).to_a.any? raise "Waited for #{timeout} seconds, but received no output matching: " \ "#{matcher.source}" end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/result_test.rb
test/result_test.rb
require_relative 'test_helper' class ThirdPartyError < RuntimeError def http_status; 400 end end class ResultTest < Minitest::Test it "sets response.body when result is a String" do mock_app { get('/') { 'Hello World' } } get '/' assert ok? assert_equal 'Hello World', body end it "sets response.body when result is an Array of Strings" do mock_app { get('/') { ['Hello', 'World'] } } get '/' assert ok? assert_equal 'HelloWorld', body end it "sets response.body when result responds to #each" do mock_app do get('/') do res = lambda { 'Hello World' } def res.each ; yield call ; end return res end end get '/' assert ok? assert_equal 'Hello World', body end it "sets response.body to [] when result is nil" do mock_app { get( '/') { nil } } get '/' assert ok? assert_equal '', body end it "sets status, headers, and body when result is a Rack response tuple" do mock_app { get('/') { [203, {'Content-Type' => 'foo/bar'}, 'Hello World'] } } get '/' assert_equal 203, status assert_equal 'foo/bar', response['Content-Type'] assert_equal 'Hello World', body end it "sets status and body when result is a two-tuple" do mock_app { get('/') { [409, 'formula of'] } } get '/' assert_equal 409, status assert_equal 'formula of', body end it "raises a ArgumentError when result is a non two or three tuple Array" do mock_app { get('/') { [409, 'formula of', 'something else', 'even more'] } } assert_raises(ArgumentError) { get '/' } end it "sets status when result is a Integer status code" do mock_app { get('/') { 205 } } get '/' assert_equal 205, status assert_equal '', body end it "sets status to 500 when raised error is not Sinatra::Error" do mock_app do set :raise_errors, false get('/') { raise ThirdPartyError } end get '/' assert_equal 500, status assert_equal '<h1>Internal Server Error</h1>', body end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/mapped_error_test.rb
test/mapped_error_test.rb
require_relative 'test_helper' class FooError < RuntimeError end class FooNotFound < Sinatra::NotFound end class FooSpecialError < Sinatra::Error def http_status; 501 end end class FooStatusOutOfRangeError < Sinatra::Error def code; 4000 end end class FooWithCode < Sinatra::Error def code; 419 end end class FirstError < RuntimeError; end class SecondError < RuntimeError; end class MappedErrorTest < Minitest::Test def test_default assert true end describe 'Exception Mappings' do it 'invokes handlers registered with ::error when raised' do mock_app do set :raise_errors, false error(FooError) { 'Foo!' } get('/') { raise FooError } end get '/' assert_equal 500, status assert_equal 'Foo!', body end it 'passes the exception object to the error handler' do mock_app do set :raise_errors, false error(FooError) { |e| assert_equal(FooError, e.class) } get('/') { raise FooError } end get('/') end it 'uses the Exception handler if no matching handler found' do mock_app do set :raise_errors, false error(Exception) { 'Exception!' } get('/') { raise FooError } end get '/' assert_equal 500, status assert_equal 'Exception!', body end it 'walks down inheritance chain for errors' do mock_app do set :raise_errors, false error(RuntimeError) { 'Exception!' } get('/') { raise FooError } end get '/' assert_equal 500, status assert_equal 'Exception!', body end it 'favors subclass handler over superclass handler if available' do mock_app do set :raise_errors, false error(Exception) { 'Exception!' } error(FooError) { 'FooError!' } error(RuntimeError) { 'Exception!' } get('/') { raise FooError } end get '/' assert_equal 500, status assert_equal 'FooError!', body end it "sets env['sinatra.error'] to the rescued exception" do mock_app do set :raise_errors, false error(FooError) do assert env.include?('sinatra.error') assert env['sinatra.error'].kind_of?(FooError) 'looks good' end get('/') { raise FooError } end get '/' assert_equal 'looks good', body end it "raises errors from the app when raise_errors set and no handler defined" do mock_app do set :raise_errors, true get('/') { raise FooError } end assert_raises(FooError) { get '/' } end it "calls error handlers before raising errors even when raise_errors is set" do mock_app do set :raise_errors, true error(FooError) { "she's there." } get('/') { raise FooError } end get '/' assert_equal 500, status end it "never raises Sinatra::NotFound beyond the application" do mock_app(Sinatra::Application) do get('/') { raise Sinatra::NotFound } end get '/' assert_equal 404, status end it "cascades for subclasses of Sinatra::NotFound" do mock_app do set :raise_errors, true error(FooNotFound) { "foo! not found." } get('/') { raise FooNotFound } end get '/' assert_equal 404, status assert_equal 'foo! not found.', body end it 'has a not_found method for backwards compatibility' do mock_app { not_found { "Lost, are we?" } } get '/test' assert_equal 404, status assert_equal "Lost, are we?", body end it 'inherits error mappings from base class' do base = Class.new(Sinatra::Base) base.error(FooError) { 'base class' } mock_app(base) do set :raise_errors, false get('/') { raise FooError } end get '/' assert_equal 'base class', body end it 'overrides error mappings in base class' do base = Class.new(Sinatra::Base) base.error(FooError) { 'base class' } mock_app(base) do set :raise_errors, false error(FooError) { 'subclass' } get('/') { raise FooError } end get '/' assert_equal 'subclass', body end it 'honors Exception#http_status if present' do mock_app do set :raise_errors, false error(501) { 'Foo!' } get('/') { raise FooSpecialError } end get '/' assert_equal 501, status assert_equal 'Foo!', body end it 'does not use Exception#code by default' do mock_app do set :raise_errors, false get('/') { raise FooWithCode } end get '/' assert_equal 500, status end it 'uses Exception#code if use_code is enabled' do mock_app do set :raise_errors, false set :use_code, true get('/') { raise FooWithCode } end get '/' assert_equal 419, status end it 'does not rely on Exception#code for invalid codes' do mock_app do set :raise_errors, false set :use_code, true get('/') { raise FooStatusOutOfRangeError } end get '/' assert_equal 500, status end it "allows a stack of exception_handlers" do mock_app do set :raise_errors, false error(FirstError) { 'First!' } error(SecondError) { 'Second!' } get('/'){ raise SecondError } end get '/' assert_equal 500, status assert_equal 'Second!', body end it "allows an exception handler to pass control to the next exception handler" do mock_app do set :raise_errors, false error(500, FirstError) { 'First!' } error(500, SecondError) { pass } get('/') { raise 500 } end get '/' assert_equal 500, status assert_equal 'First!', body end it "allows an exception handler to handle the exception" do mock_app do set :raise_errors, false error(500, FirstError) { 'First!' } error(500, SecondError) { 'Second!' } get('/') { raise 500 } end get '/' assert_equal 500, status assert_equal 'Second!', body end end describe 'Custom Error Pages' do it 'allows numeric status code mappings to be registered with ::error' do mock_app do set :raise_errors, false error(500) { 'Foo!' } get('/') { [500, {}, 'Internal Foo Error'] } end get '/' assert_equal 500, status assert_equal 'Foo!', body end it 'allows ranges of status code mappings to be registered with :error' do mock_app do set :raise_errors, false error(500..550) { "Error: #{response.status}" } get('/') { [507, {}, 'A very special error'] } end get '/' assert_equal 507, status assert_equal 'Error: 507', body end it 'allows passing more than one range' do mock_app do set :raise_errors, false error(409..411, 503..509) { "Error: #{response.status}" } get('/') { [507, {}, 'A very special error'] } end get '/' assert_equal 507, status assert_equal 'Error: 507', body end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/slim_test.rb
test/slim_test.rb
require_relative 'test_helper' begin require 'slim' class SlimTest < Minitest::Test def slim_app(&block) mock_app do set :views, __dir__ + '/views' get('/', &block) end get '/' end it 'renders inline slim strings' do slim_app { slim "h1 Hiya\n" } assert ok? assert_equal "<h1>Hiya</h1>", body end it 'renders .slim files in views path' do slim_app { slim :hello } assert ok? assert_equal "<h1>Hello From Slim</h1>", body end it "renders with inline layouts" do mock_app do layout { %(h1\n | THIS. IS. \n == yield.upcase ) } get('/') { slim 'em Sparta' } end get '/' assert ok? assert_equal "<h1>THIS. IS. <EM>SPARTA</EM></h1>", body end it "renders with file layouts" do slim_app { slim('| Hello World', :layout => :layout2) } assert ok? assert_equal "<h1>Slim Layout!</h1><p>Hello World</p>", body end it "raises error if template not found" do mock_app { get('/') { slim(:no_such_template) } } assert_raises(Errno::ENOENT) { get('/') } end HTML4_DOCTYPE = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" it "passes slim options to the slim engine" do mock_app { get('/') { slim("x foo='bar'", :attr_quote => "'") }} get '/' assert ok? assert_body "<x foo='bar'></x>" end it "passes default slim options to the slim engine" do mock_app do set :slim, :attr_quote => "'" get('/') { slim("x foo='bar'") } end get '/' assert ok? assert_body "<x foo='bar'></x>" end it "merges the default slim options with the overrides and passes them to the slim engine" do mock_app do set :slim, :attr_quote => "'" get('/') { slim("x foo='bar'") } get('/other') { slim("x foo='bar'", :attr_quote => '"') } end get '/' assert ok? assert_body "<x foo='bar'></x>" get '/other' assert ok? assert_body '<x foo="bar"></x>' end it "can render truly nested layouts by accepting a layout and a block with the contents" do mock_app do template(:main_outer_layout) { "h1 Title\n== yield" } template(:an_inner_layout) { "h2 Subtitle\n== yield" } template(:a_page) { "p Contents." } get('/') do slim :main_outer_layout, :layout => false do slim :an_inner_layout do slim :a_page end end end end get '/' assert ok? assert_body "<h1>Title</h1>\n<h2>Subtitle</h2>\n<p>Contents.</p>\n" end end rescue LoadError warn "#{$!}: skipping slim tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/erb_test.rb
test/erb_test.rb
require_relative 'test_helper' class ERBTest < Minitest::Test def engine Tilt::ERBTemplate end def setup Tilt.prefer engine, :erb super end def erb_app(&block) mock_app do set :views, __dir__ + '/views' get('/', &block) end get '/' end it 'uses the correct engine' do assert_equal engine, Tilt[:erb] end it 'renders inline ERB strings' do erb_app { erb '<%= 1 + 1 %>' } assert ok? assert_equal '2', body end it 'renders .erb files in views path' do erb_app { erb :hello } assert ok? assert_equal "Hello World\n", body end it 'takes a :locals option' do erb_app do locals = {:foo => 'Bar'} erb '<%= foo %>', :locals => locals end assert ok? assert_equal 'Bar', body end it "renders with inline layouts" do mock_app do layout { 'THIS. IS. <%= yield.upcase %>!' } get('/') { erb 'Sparta' } end get '/' assert ok? assert_equal 'THIS. IS. SPARTA!', body end it "renders with file layouts" do erb_app { erb 'Hello World', :layout => :layout2 } assert ok? assert_body "ERB Layout!\nHello World" end it "renders erb with blocks" do mock_app do def container @_out_buf << "THIS." yield @_out_buf << "SPARTA!" end def is; "IS." end get('/') { erb '<% container do %> <%= is %> <% end %>' } end get '/' assert ok? assert_equal 'THIS. IS. SPARTA!', body end it "can be used in a nested fashion for partials and whatnot" do mock_app do template(:inner) { "<inner><%= 'hi' %></inner>" } template(:outer) { "<outer><%= erb :inner %></outer>" } get('/') { erb :outer } end get '/' assert ok? assert_equal '<outer><inner>hi</inner></outer>', body end it "can render truly nested layouts by accepting a layout and a block with the contents" do mock_app do template(:main_outer_layout) { "<h1>Title</h1>\n<%= yield %>" } template(:an_inner_layout) { "<h2>Subtitle</h2>\n<%= yield %>" } template(:a_page) { "<p>Contents.</p>\n" } get('/') do erb :main_outer_layout, :layout => false do erb :an_inner_layout do erb :a_page end end end end get '/' assert ok? assert_body "<h1>Title</h1>\n<h2>Subtitle</h2>\n<p>Contents.</p>\n" end end begin require 'erubi' class ErubiTest < ERBTest def engine; Tilt::ErubiTemplate end end rescue LoadError warn "#{$!}: skipping erubi tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/rdoc_test.rb
test/rdoc_test.rb
require_relative 'test_helper' begin require 'rdoc' require 'rdoc/markup/to_html' class RdocTest < Minitest::Test def rdoc_app(&block) mock_app do set :views, __dir__ + '/views' get('/', &block) end get '/' end it 'renders inline rdoc strings' do rdoc_app { rdoc '= Hiya' } assert ok? assert_body(/<h1[^>]*>(<.*>)?Hiya(<.*>)?<\/h1>/) end it 'renders .rdoc files in views path' do rdoc_app { rdoc :hello } assert ok? assert_body(/<h1[^>]*>(<.*>)?Hello From RDoc(<.*>)?<\/h1>/) end it "raises error if template not found" do mock_app { get('/') { rdoc :no_such_template } } assert_raises(Errno::ENOENT) { get('/') } end it "renders with inline layouts" do mock_app do layout { 'THIS. IS. #{yield.upcase}!' } get('/') { rdoc 'Sparta', :layout_engine => :str } end get '/' assert ok? assert_like 'THIS. IS. <P>SPARTA</P>!', body end it "renders with file layouts" do rdoc_app { rdoc 'Hello World', :layout => :layout2, :layout_engine => :erb } assert ok? assert_body "ERB Layout!\n<p>Hello World</p>" end it "can be used in a nested fashion for partials and whatnot" do mock_app do template(:inner) { "hi" } template(:outer) { "<outer><%= rdoc :inner %></outer>" } get('/') { erb :outer } end get '/' assert ok? assert_like '<outer><p>hi</p></outer>', body end end rescue LoadError warn "#{$!}: skipping rdoc tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/host_authorization_test.rb
test/host_authorization_test.rb
# frozen_string_literal: true require_relative "test_helper" class HostAuthorization < Minitest::Test describe "in development environment" do setup do Sinatra::Base.set :environment, :development end %w[ 127.0.0.1 127.0.0.1:3000 [::1] [::1]:3000 localhost localhost:3000 foo.localhost foo.test ].each do |development_host| it "allows a host like '#{development_host}'" do mock_app do get("/") { "OK" } end headers = { "HTTP_HOST" => development_host } request = Rack::MockRequest.new(@app) response = request.get("/", headers) assert_equal 200, response.status assert_equal "OK", response.body end end it "stops non-development hosts by default" do mock_app { get("/") { "OK" } } get "/", { "HTTP_HOST" => "example.com" } assert_equal 403, response.status assert_equal "Host not permitted", body end it "allows any requests when no permitted hosts are specified" do mock_app do set :host_authorization, { permitted_hosts: [] } get("/") { "OK" } end get "/", { "HTTP_HOST" => "example.com" } assert_equal 200, response.status assert_equal "OK", body end end describe "in non-development environments" do it "allows requests based on the permitted hosts specified" do allowed_host = "allowed.org" mock_app do set :host_authorization, { permitted_hosts: [allowed_host] } get("/") { "OK" } end headers = { "HTTP_HOST" => allowed_host } request = Rack::MockRequest.new(@app) response = request.get("/", headers) assert_equal 200, response.status assert_equal "OK", response.body end it "stops requests based on the permitted hosts specified" do allowed_host = "allowed.org" mock_app do set :host_authorization, { permitted_hosts: [allowed_host] } get("/") { "OK" } end headers = { "HTTP_HOST" => "bad-host.org" } request = Rack::MockRequest.new(@app) response = request.get("/", headers) assert_equal 403, response.status assert_equal "Host not permitted", response.body end it "defaults to permit any hosts" do mock_app do get("/") { "OK" } end headers = { "HTTP_HOST" => "some-host.org" } request = Rack::MockRequest.new(@app) response = request.get("/", headers) assert_equal 200, response.status assert_equal "OK", response.body end it "stops the request using the configured response" do allowed_host = "allowed.org" status = 418 message = "No coffee for you" mock_app do set :host_authorization, { permitted_hosts: [allowed_host], status: status, message: message, } get("/") { "OK" } end headers = { "HTTP_HOST" => "bad-host.org" } request = Rack::MockRequest.new(@app) response = request.get("/", headers) assert_equal status, response.status assert_equal message, response.body end it "allows custom logic with 'allow_if'" do allowed_host = "allowed.org" mock_app do set :host_authorization, { permitted_hosts: [allowed_host], allow_if: ->(env) do request = Sinatra::Request.new(env) request.path == "/allowed" end } get("/") { "OK" } get("/allowed") { "OK" } end headers = { "HTTP_HOST" => "some-host.org" } request = Rack::MockRequest.new(@app) response = request.get("/allowed", headers) assert_equal 200, response.status assert_equal "OK", response.body request = Rack::MockRequest.new(@app) response = request.get("/", headers) assert_equal 403, response.status end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/markaby_test.rb
test/markaby_test.rb
require_relative 'test_helper' begin require 'markaby' class MarkabyTest < Minitest::Test def markaby_app(&block) mock_app do set :views, __dir__ + '/views' get('/', &block) end get '/' end it 'renders inline markaby strings' do markaby_app { markaby 'h1 "Hiya"' } assert ok? assert_equal "<h1>Hiya</h1>", body end it 'renders .markaby files in views path' do markaby_app { markaby :hello } assert ok? assert_equal "<h1>Hello From Markaby</h1>", body end it "renders with inline layouts" do mock_app do layout { 'h1 { text "THIS. IS. "; yield }' } get('/') { markaby 'em "SPARTA"' } end get '/' assert ok? assert_equal "<h1>THIS. IS. <em>SPARTA</em></h1>", body end it "renders with file layouts" do markaby_app { markaby 'text "Hello World"', :layout => :layout2 } assert ok? assert_equal "<h1>Markaby Layout!</h1><p>Hello World</p>", body end it 'renders inline markaby blocks' do markaby_app { markaby { h1 'Hiya' } } assert ok? assert_equal "<h1>Hiya</h1>", body end it 'renders inline markaby blocks with inline layouts' do markaby_app do settings.layout { 'h1 { text "THIS. IS. "; yield }' } markaby { em 'SPARTA' } end assert ok? assert_equal "<h1>THIS. IS. <em>SPARTA</em></h1>", body end it 'renders inline markaby blocks with file layouts' do markaby_app { markaby(:layout => :layout2) { text "Hello World" } } assert ok? assert_equal "<h1>Markaby Layout!</h1><p>Hello World</p>", body end it "raises error if template not found" do mock_app { get('/') { markaby :no_such_template } } assert_raises(Errno::ENOENT) { get('/') } end it "allows passing locals" do markaby_app { markaby 'text value', :locals => { :value => 'foo' } } assert ok? assert_equal 'foo', body end end rescue LoadError warn "#{$!}: skipping markaby tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/settings_test.rb
test/settings_test.rb
require_relative 'test_helper' class SettingsTest < Minitest::Test setup do @base = Sinatra.new(Sinatra::Base) @base.set :environment => :foo, :app_file => nil @application = Sinatra.new(Sinatra::Application) @application.set :environment => :foo, :app_file => nil end it 'sets settings to literal values' do @base.set(:foo, 'bar') assert @base.respond_to?(:foo) assert_equal 'bar', @base.foo end it 'sets settings to Procs' do @base.set(:foo, Proc.new { 'baz' }) assert @base.respond_to?(:foo) assert_equal 'baz', @base.foo end it 'sets settings using a block' do @base.set(:foo){ 'baz' } assert @base.respond_to?(:foo) assert_equal 'baz', @base.foo end it 'raises an error with a value and a block' do assert_raises ArgumentError do @base.set(:fiz, 'boom!'){ 'baz' } end assert !@base.respond_to?(:fiz) end it 'raises an error without value and block' do assert_raises(ArgumentError) { @base.set(:fiz) } assert !@base.respond_to?(:fiz) end it 'allows setting a value to the app class' do @base.set :base, @base assert @base.respond_to?(:base) assert_equal @base, @base.base end it 'raises an error with the app class as value and a block' do assert_raises ArgumentError do @base.set(:fiz, @base) { 'baz' } end assert !@base.respond_to?(:fiz) end it "sets multiple settings with a Hash" do @base.set :foo => 1234, :bar => 'Hello World', :baz => Proc.new { 'bizzle' } assert_equal 1234, @base.foo assert_equal 'Hello World', @base.bar assert_equal 'bizzle', @base.baz end it 'sets multiple settings using #each' do @base.set [["foo", "bar"]] assert_equal "bar", @base.foo end it 'inherits settings methods when subclassed' do @base.set :foo, 'bar' @base.set :biz, Proc.new { 'baz' } sub = Class.new(@base) assert sub.respond_to?(:foo) assert_equal 'bar', sub.foo assert sub.respond_to?(:biz) assert_equal 'baz', sub.biz end it 'overrides settings in subclass' do @base.set :foo, 'bar' @base.set :biz, Proc.new { 'baz' } sub = Class.new(@base) sub.set :foo, 'bling' assert_equal 'bling', sub.foo assert_equal 'bar', @base.foo end it 'creates setter methods when first defined' do @base.set :foo, 'bar' assert @base.respond_to?('foo=') @base.foo = 'biz' assert_equal 'biz', @base.foo end it 'creates predicate methods when first defined' do @base.set :foo, 'hello world' assert @base.respond_to?(:foo?) assert @base.foo? @base.set :foo, nil assert !@base.foo? end it 'uses existing setter methods if detected' do class << @base def foo @foo end def foo=(value) @foo = 'oops' end end @base.set :foo, 'bam' assert_equal 'oops', @base.foo end it 'merges values of multiple set calls if those are hashes' do @base.set :foo, :a => 1 sub = Class.new(@base) sub.set :foo, :b => 2 assert_equal({:a => 1, :b => 2}, sub.foo) end it 'merging does not affect the superclass' do @base.set :foo, :a => 1 sub = Class.new(@base) sub.set :foo, :b => 2 assert_equal({:a => 1}, @base.foo) end it 'is possible to change a value from a hash to something else' do @base.set :foo, :a => 1 @base.set :foo, :bar assert_equal(:bar, @base.foo) end it 'merges values with values of the superclass if those are hashes' do @base.set :foo, :a => 1 @base.set :foo, :b => 2 assert_equal({:a => 1, :b => 2}, @base.foo) end it "sets multiple settings to true with #enable" do @base.enable :sessions, :foo, :bar assert @base.sessions assert @base.foo assert @base.bar end it "sets multiple settings to false with #disable" do @base.disable :sessions, :foo, :bar assert !@base.sessions assert !@base.foo assert !@base.bar end it 'is accessible from instances via #settings' do assert_equal :foo, @base.new!.settings.environment end it 'is accessible from class via #settings' do assert_equal :foo, @base.settings.environment end describe 'default_content_type' do it 'defaults to html' do assert_equal 'text/html', @base.default_content_type end it 'can be changed' do @base.set :default_content_type, 'application/json' @base.get('/') { '{"a":1}' } @app = @base get '/' assert_equal 200, status assert_equal 'application/json', response.content_type end it 'can be disabled' do @base.set :default_content_type, nil @base.error(404) { "" } @app = @base get '/' assert_equal 404, status assert_nil response.content_type assert_empty body end it 'may emit content without a content-type (to be sniffed)' do @base.set :default_content_type, nil @base.get('/') { raise Sinatra::BadRequest, "This is a drill" } @app = @base get '/' assert_equal 400, status assert_nil response.content_type assert_body "This is a drill" end end describe 'methodoverride' do it 'is disabled on Base' do assert ! @base.method_override? end it 'is enabled on Application' do assert @application.method_override? end it 'enables MethodOverride middleware' do @base.set :method_override, true @base.put('/') { 'okay' } @app = @base post '/', {'_method'=>'PUT'}, {} assert_equal 200, status assert_equal 'okay', body end it 'is backward compatible with methodoverride' do assert ! @base.methodoverride? @base.enable :methodoverride assert @base.methodoverride? end it 'ignores bundler/inline from callers' do @application.stub(:caller, ->(_){ ['/path/to/bundler/inline.rb', $0] }) do assert_equal File.expand_path($0), File.expand_path(@application.send(:caller_files).first) end end end describe 'run' do it 'is disabled on Base' do assert ! @base.run? end it 'is enabled on Application except in test environment' do assert @application.run? @application.set :environment, :test assert ! @application.run? end end describe 'raise_errors' do it 'is enabled on Base only in test' do assert ! @base.raise_errors? @base.set(:environment, :test) assert @base.raise_errors? end it 'is enabled on Application only in test' do assert ! @application.raise_errors? @application.set(:environment, :test) assert @application.raise_errors? end end describe 'show_exceptions' do it 'is disabled on Base except under development' do assert ! @base.show_exceptions? @base.environment = :development assert @base.show_exceptions? end it 'is disabled on Application except in development' do assert ! @application.show_exceptions? @application.set(:environment, :development) assert @application.show_exceptions? end it 'returns a friendly 500' do klass = Sinatra.new(Sinatra::Application) mock_app(klass) { enable :show_exceptions get '/' do raise StandardError end } get '/' assert_equal 500, status assert body.include?("StandardError") assert body.include?("<code>show_exceptions</code> setting") end it 'does not attempt to show unparsable query parameters' do klass = Sinatra.new(Sinatra::Application) mock_app(klass) { enable :show_exceptions get '/' do raise Sinatra::BadRequest end } get '/' assert_equal 400, status refute body.include?('<div id="get">') refute body.include?('<div id="post">') end it 'does not override app-specified error handling when set to :after_handler' do ran = false mock_app do set :show_exceptions, :after_handler error(RuntimeError) { ran = true } get('/') { raise RuntimeError } end get '/' assert_equal 500, status assert ran end it 'does catch any other exceptions when set to :after_handler' do ran = false mock_app do set :show_exceptions, :after_handler error(RuntimeError) { ran = true } get('/') { raise ArgumentError } end get '/' assert_equal 500, status assert !ran end end describe 'dump_errors' do it 'is disabled on Base in test' do @base.environment = :test assert ! @base.dump_errors? @base.environment = :development assert @base.dump_errors? @base.environment = :production assert @base.dump_errors? end it 'dumps exception with backtrace to rack.errors' do klass = Sinatra.new(Sinatra::Application) mock_app(klass) { enable :dump_errors disable :raise_errors error do error = @env['rack.errors'].instance_variable_get(:@error) error.rewind error.read end get '/' do raise end } get '/' assert body.include?("RuntimeError") && body.include?("settings_test.rb") end it 'does not dump 404 errors' do klass = Sinatra.new(Sinatra::Application) mock_app(klass) { enable :dump_errors disable :raise_errors error do error = @env['rack.errors'].instance_variable_get(:@error) error.rewind error.read end get '/' do raise Sinatra::NotFound end } get '/' assert !body.include?("NotFound") && !body.include?("settings_test.rb") end end describe 'sessions' do it 'is disabled on Base' do assert ! @base.sessions? end it 'is disabled on Application' do assert ! @application.sessions? end end describe 'logging' do it 'is disabled on Base' do assert ! @base.logging? end it 'is enabled on Application except in test environment' do assert @application.logging? @application.set :environment, :test assert ! @application.logging end end describe 'static' do it 'is disabled on Base by default' do assert ! @base.static? end it 'is enabled on Base when public_folder is set and exists' do @base.set :environment, :development @base.set :public_folder, __dir__ assert @base.static? end it 'is enabled on Base when root is set and root/public_folder exists' do @base.set :environment, :development @base.set :root, __dir__ assert @base.static? end it 'is disabled on Application by default' do assert ! @application.static? end it 'is enabled on Application when public_folder is set and exists' do @application.set :environment, :development @application.set :public_folder, __dir__ assert @application.static? end it 'is enabled on Application when root is set and root/public_folder exists' do @application.set :environment, :development @application.set :root, __dir__ assert @application.static? end it 'is possible to use Module#public' do @base.send(:define_method, :foo) { } @base.send(:private, :foo) assert !@base.public_method_defined?(:foo) @base.send(:public, :foo) assert @base.public_method_defined?(:foo) end it 'is possible to use the keyword public in a sinatra app' do app = Sinatra.new do private def priv; end public def pub; end end assert !app.public_method_defined?(:priv) assert app.public_method_defined?(:pub) end end describe 'bind' do it 'defaults to 0.0.0.0' do assert_equal '0.0.0.0', @base.bind assert_equal '0.0.0.0', @application.bind end end describe 'port' do it 'defaults to 4567' do assert_equal 4567, @base.port assert_equal 4567, @application.port end end describe 'server' do it 'includes webrick' do assert @base.server.include?('webrick') assert @application.server.include?('webrick') end it 'includes puma' do assert @base.server.include?('puma') assert @application.server.include?('puma') end it 'includes falcon on non-jruby' do if RUBY_ENGINE != 'jruby' assert @base.server.include?('falcon') assert @application.server.include?('falcon') else assert !@base.server.include?('falcon') assert !@application.server.include?('falcon') end end end describe 'app_file' do it 'is nil for base classes' do assert_nil Sinatra::Base.app_file assert_nil Sinatra::Application.app_file end it 'defaults to the file subclassing' do assert_equal File.expand_path(__FILE__), Sinatra.new.app_file end end describe 'root' do it 'is nil if app_file is not set' do assert_nil @base.root assert_nil @application.root end it 'is equal to the expanded basename of app_file' do @base.app_file = __FILE__ assert_equal File.expand_path(__dir__), @base.root @application.app_file = __FILE__ assert_equal File.expand_path(__dir__), @application.root end end describe 'views' do it 'is nil if root is not set' do assert_nil @base.views assert_nil @application.views end it 'is set to root joined with views/' do @base.root = __dir__ assert_equal __dir__ + "/views", @base.views @application.root = __dir__ assert_equal __dir__ + "/views", @application.views end end describe 'public_folder' do it 'is nil if root is not set' do assert_nil @base.public_folder assert_nil @application.public_folder end it 'is set to root joined with public/' do @base.root = __dir__ assert_equal __dir__ + "/public", @base.public_folder @application.root = __dir__ assert_equal __dir__ + "/public", @application.public_folder end end describe 'public_dir' do it 'is an alias for public_folder' do @base.public_dir = __dir__ assert_equal __dir__, @base.public_dir assert_equal @base.public_folder, @base.public_dir @application.public_dir = __dir__ assert_equal __dir__, @application.public_dir assert_equal @application.public_folder, @application.public_dir end end describe 'lock' do it 'is disabled by default' do assert ! @base.lock? assert ! @application.lock? end end describe 'protection' do class MiddlewareTracker < Rack::Builder def self.track Rack.send :remove_const, :Builder Rack.const_set :Builder, MiddlewareTracker MiddlewareTracker.used.clear yield ensure Rack.send :remove_const, :Builder Rack.const_set :Builder, MiddlewareTracker.superclass end def self.used @used ||= [] end def use(middleware, *) MiddlewareTracker.used << middleware super end end it 'sets up Rack::Protection' do MiddlewareTracker.track do Sinatra::Base.new assert_include MiddlewareTracker.used, Rack::Protection end end it 'sets up Rack::Protection::PathTraversal' do MiddlewareTracker.track do Sinatra::Base.new assert_include MiddlewareTracker.used, Rack::Protection::PathTraversal end end it 'does not set up Rack::Protection::PathTraversal when disabling it' do MiddlewareTracker.track do Sinatra.new { set :protection, :except => :path_traversal }.new assert_include MiddlewareTracker.used, Rack::Protection assert !MiddlewareTracker.used.include?(Rack::Protection::PathTraversal) end end it 'sets up RemoteToken if sessions are enabled' do MiddlewareTracker.track do Sinatra.new { enable :sessions }.new assert_include MiddlewareTracker.used, Rack::Protection::RemoteToken end end it 'sets up RemoteToken if sessions are enabled with a custom session store' do MiddlewareTracker.track do Sinatra.new { enable :sessions set :session_store, Rack::Session::Pool }.new assert_include MiddlewareTracker.used, Rack::Session::Pool assert_include MiddlewareTracker.used, Rack::Protection::RemoteToken end end it 'does not set up RemoteToken if sessions are disabled' do MiddlewareTracker.track do Sinatra.new.new assert !MiddlewareTracker.used.include?(Rack::Protection::RemoteToken) end end it 'sets up RemoteToken if it is configured to' do MiddlewareTracker.track do Sinatra.new { set :protection, :session => true }.new assert_include MiddlewareTracker.used, Rack::Protection::RemoteToken end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/base_test.rb
test/base_test.rb
require_relative 'test_helper' class BaseTest < Minitest::Test describe 'Sinatra::Base subclasses' do class TestApp < Sinatra::Base get('/') { 'Hello World' } end class TestKeywordArgumentInitializerApp < Sinatra::Base def initialize(argument:) @argument = argument end get('/') { "Hello World with Keyword Arguments: #{@argument}" } end it 'include Rack::Utils' do assert TestApp.included_modules.include?(Rack::Utils) end it 'processes requests with #call' do assert TestApp.respond_to?(:call) request = Rack::MockRequest.new(TestApp) response = request.get('/') assert response.ok? assert_equal 'Hello World', response.body end class TestApp < Sinatra::Base get '/state' do @foo ||= "new" body = "Foo: #{@foo}" @foo = 'discard' body end end it 'does not maintain state between requests' do request = Rack::MockRequest.new(TestApp) 2.times do response = request.get('/state') assert response.ok? assert_equal 'Foo: new', response.body end end it "passes the subclass to configure blocks" do ref = nil TestApp.configure { |app| ref = app } assert_equal TestApp, ref end it "allows the configure block arg to be omitted and does not change context" do context = nil TestApp.configure { context = self } assert_equal self, context end it "allows constructor to receive keyword arguments" do app = TestKeywordArgumentInitializerApp.new(argument: "some argument") request = Rack::MockRequest.new(app) response = request.get('/') assert response.ok? assert_equal 'Hello World with Keyword Arguments: some argument', response.body end end describe "Sinatra::Base#new" do it 'returns a wrapper' do assert_equal Sinatra::Wrapper, Sinatra::Base.new.class end it 'implements a nice inspect' do assert_equal '#<Sinatra::Base app_file=nil>', Sinatra::Base.new.inspect end it 'exposes settings' do assert_equal Sinatra::Base.settings, Sinatra::Base.new.settings end it 'exposes helpers' do assert_equal 'image/jpeg', Sinatra::Base.new.helpers.mime_type(:jpg) end end describe "Sinatra::Base as Rack middleware" do app = lambda { |env| headers = {'X-Downstream' => 'true'} headers['X-Route-Missing'] = env['sinatra.route-missing'] || '' [210, headers, ['Hello from downstream']] } class TestMiddleware < Sinatra::Base end it 'creates a middleware that responds to #call with .new' do middleware = TestMiddleware.new(app) assert middleware.respond_to?(:call) end it 'exposes the downstream app' do middleware = TestMiddleware.new!(app) assert_same app, middleware.app end class TestMiddleware < Sinatra::Base def route_missing env['sinatra.route-missing'] = '1' super end get('/') { 'Hello from middleware' } end middleware = TestMiddleware.new(app) request = Rack::MockRequest.new(middleware) it 'intercepts requests' do response = request.get('/') assert response.ok? assert_equal 'Hello from middleware', response.body end it 'automatically forwards requests downstream when no matching route found' do response = request.get('/missing') assert_equal 210, response.status assert_equal 'Hello from downstream', response.body end it 'calls #route_missing before forwarding downstream' do response = request.get('/missing') assert_equal '1', response['X-Route-Missing'] end class TestMiddleware < Sinatra::Base get('/low-level-forward') { app.call(env) } end it 'can call the downstream app directly and return result' do response = request.get('/low-level-forward') assert_equal 210, response.status assert_equal 'true', response['X-Downstream'] assert_equal 'Hello from downstream', response.body end class TestMiddleware < Sinatra::Base get '/explicit-forward' do response['X-Middleware'] = 'true' res = forward assert_nil res assert_equal 210, response.status assert_equal 'true', response['X-Downstream'] assert_equal ['Hello from downstream'], response.body 'Hello after explicit forward' end end it 'forwards the request downstream and integrates the response into the current context' do response = request.get('/explicit-forward') assert_equal 210, response.status assert_equal 'true', response['X-Downstream'] assert_equal 'Hello after explicit forward', response.body assert_equal '28', response['Content-Length'] end app_content_length = lambda {|env| [200, {'Content-Length' => '16'}, 'From downstream!']} class TestMiddlewareContentLength < Sinatra::Base get '/forward' do 'From after explicit forward!' end end middleware_content_length = TestMiddlewareContentLength.new(app_content_length) request_content_length = Rack::MockRequest.new(middleware_content_length) it "sets content length for last response" do response = request_content_length.get('/forward') assert_equal '28', response['Content-Length'] end it 'formats integer values correctly in Content-Type parameters' do mock_app do get('/') do content_type "foo/bar", baz: 1 'Ok' end end get '/' assert_equal 'foo/bar;baz=1', response['Content-Type'] end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/scss_test.rb
test/scss_test.rb
require_relative 'test_helper' begin require 'sass-embedded' class ScssTest < Minitest::Test def scss_app(options = {}, &block) mock_app do set :views, __dir__ + '/views' set options get('/', &block) end get '/' end it 'renders inline Scss strings' do scss_app { scss "#scss {\n background-color: white; }\n" } assert ok? assert_equal "#scss {\n background-color: white;\n}", body end it 'defaults content type to css' do scss_app { scss "#scss {\n background-color: white; }\n" } assert ok? assert_equal "text/css;charset=utf-8", response['Content-Type'] end it 'defaults allows setting content type per route' do scss_app do content_type :html scss "#scss {\n background-color: white; }\n" end assert ok? assert_equal "text/html;charset=utf-8", response['Content-Type'] end it 'defaults allows setting content type globally' do scss_app(:scss => { :content_type => 'html' }) { scss "#scss {\n background-color: white; }\n" } assert ok? assert_equal "text/html;charset=utf-8", response['Content-Type'] end it 'renders .scss files in views path' do scss_app { scss :hello } assert ok? assert_equal "#scss {\n background-color: white;\n}", body end it 'ignores the layout option' do scss_app { scss :hello, :layout => :layout2 } assert ok? assert_equal "#scss {\n background-color: white;\n}", body end it "raises error if template not found" do mock_app { get('/') { scss(:no_such_template) } } assert_raises(Errno::ENOENT) { get('/') } end it "passes scss options to the scss engine" do scss_app do scss( "#scss {\n background-color: white;\n color: black\n}", :style => :compressed ) end assert ok? assert_equal "#scss{background-color:#fff;color:#000}", body end it "passes default scss options to the scss engine" do mock_app do set :scss, {:style => :compressed} # default scss style is :expanded get('/') { scss("#scss {\n background-color: white;\n color: black;\n}") } end get '/' assert ok? assert_equal "#scss{background-color:#fff;color:#000}", body end end rescue LoadError warn "#{$!}: skipping scss tests" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/integration/gemfile_without_rackup.rb
test/integration/gemfile_without_rackup.rb
# frozen_string_literal: true source 'https://rubygems.org' gemspec path: File.join('..', '..')
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/integration/zeitwerk_app.rb
test/integration/zeitwerk_app.rb
require "bundler/setup" # This needs to come first so that sinatra require goes through zeitwerk loader require "zeitwerk" require "sinatra" get "/" do "OK" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/integration/app.rb
test/integration/app.rb
$stderr.puts "loading" require 'sinatra' configure do set :foo, :bar end get '/app_file' do content_type :txt settings.app_file end get '/ping' do 'pong' end get '/stream' do stream do |out| sleep 0.1 out << "a" sleep 1.25 out << "b" end end get '/mainonly' do object = Object.new begin object.send(:get, '/foo') { } 'false' rescue NameError 'true' end end set :out, nil get '/async' do stream(:keep_open) { |o| (settings.out = o) << "hi!"; sleep 1 } end get '/send' do settings.out << params[:msg] if params[:msg] settings.out.close if params[:close] "ok" end get '/send_file' do file = File.expand_path '../views/a/in_a.str', __dir__ send_file file end get '/streaming' do headers['Content-Length'] = '46' stream do |out| out << "It's gonna be legen -\n" sleep 0.5 out << " (wait for it) \n" puts headers sleep 1 out << "- dary!\n" end end class Subclass < Sinatra::Base set :out, nil get '/subclass/async' do stream(:keep_open) { |o| (settings.out = o) << "hi!"; sleep 1 } end get '/subclass/send' do settings.out << params[:msg] if params[:msg] settings.out.close if params[:close] "ok" end end use Subclass $stderr.puts "starting"
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/test/integration/simple_app.rb
test/integration/simple_app.rb
require "bundler/setup" require "sinatra" get "/" do "OK" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/examples/chat.rb
examples/chat.rb
#!/usr/bin/env ruby -I ../lib -I lib # frozen_string_literal: true # This example does *not* work properly with WEBrick or other # servers that buffer output. To shut down the server, close any # open browser tabs that are connected to the chat server. require 'sinatra' set :server, :puma connections = Set.new get '/' do halt erb(:login) unless params[:user] erb :chat, locals: { user: params[:user].gsub(/\W/, '') } end get '/stream', provides: 'text/event-stream' do stream :keep_open do |out| if connections.add?(out) out.callback { connections.delete(out) } end out << "heartbeat:\n" sleep 1 rescue out.close end end post '/' do connections.each do |out| out << "data: #{params[:msg]}\n\n" rescue out.close end 204 # response without entity body end __END__ @@ layout <html> <head> <title>Super Simple Chat with Sinatra</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> </head> <body><%= yield %></body> </html> @@ login <form action="/"> <label for='user'>User Name:</label> <input name="user" value="" /> <input type="submit" value="GO!" /> </form> @@ chat <pre id='chat'></pre> <form> <input id='msg' placeholder='type message here...' /> </form> <script> // reading var es = new EventSource('/stream'); es.onmessage = function(e) { $('#chat').append(e.data + "\n") }; // writing $("form").on('submit',function(e) { $.post('/', {msg: "<%= user %>: " + $('#msg').val()}); $('#msg').val(''); $('#msg').focus(); e.preventDefault(); }); </script>
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/examples/lifecycle_events.rb
examples/lifecycle_events.rb
#!/usr/bin/env ruby -I ../lib -I lib # frozen_string_literal: true require 'sinatra' get('/') do 'This shows how lifecycle events work' end on_start do puts "==============" puts " Booting up" puts "==============" end on_stop do puts "=================" puts " Shutting down" puts "=================" end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/examples/simple.rb
examples/simple.rb
#!/usr/bin/env ruby -I ../lib -I lib # frozen_string_literal: true require 'sinatra' get('/') { 'this is a simple app' }
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/lib/sinatra.rb
lib/sinatra.rb
# frozen_string_literal: true require 'sinatra/main' enable :inline_templates
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/lib/sinatra/main.rb
lib/sinatra/main.rb
# frozen_string_literal: true module Sinatra PARAMS_CONFIG = {} if ARGV.any? require 'optparse' parser = OptionParser.new do |op| op.on('-p port', 'set the port (default is 4567)') { |val| PARAMS_CONFIG[:port] = Integer(val) } op.on('-s server', 'specify rack server/handler') { |val| PARAMS_CONFIG[:server] = val } op.on('-q', 'turn on quiet mode (default is off)') { PARAMS_CONFIG[:quiet] = true } op.on('-x', 'turn on the mutex lock (default is off)') { PARAMS_CONFIG[:lock] = true } op.on('-e env', 'set the environment (default is development)') do |val| ENV['RACK_ENV'] = val PARAMS_CONFIG[:environment] = val.to_sym end op.on('-o addr', "set the host (default is (env == 'development' ? 'localhost' : '0.0.0.0'))") do |val| PARAMS_CONFIG[:bind] = val end end begin parser.parse!(ARGV.dup) rescue StandardError => e PARAMS_CONFIG[:optparse_error] = e end end require 'sinatra/base' class Application < Base # we assume that the first file that requires 'sinatra' is the # app_file. all other path related options are calculated based # on this path by default. set :app_file, caller_files.first || $0 set :run, proc { File.expand_path($0) == File.expand_path(app_file) } if run? && ARGV.any? error = PARAMS_CONFIG.delete(:optparse_error) raise error if error PARAMS_CONFIG.each { |k, v| set k, v } end end remove_const(:PARAMS_CONFIG) at_exit { Application.run! if $!.nil? && Application.run? } end # include would include the module in Object # extend only extends the `main` object extend Sinatra::Delegator class Rack::Builder include Sinatra::Delegator end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/lib/sinatra/version.rb
lib/sinatra/version.rb
# frozen_string_literal: true module Sinatra VERSION = '4.2.1' end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/lib/sinatra/base.rb
lib/sinatra/base.rb
# frozen_string_literal: true # external dependencies require 'rack' begin require 'rackup' rescue LoadError end require 'tilt' require 'rack/protection' require 'rack/session' require 'mustermann' require 'mustermann/sinatra' require 'mustermann/regular' # stdlib dependencies require 'ipaddr' require 'time' require 'uri' # other files we need require 'sinatra/indifferent_hash' require 'sinatra/show_exceptions' require 'sinatra/version' require_relative 'middleware/logger' module Sinatra # The request object. See Rack::Request for more info: # https://rubydoc.info/github/rack/rack/main/Rack/Request class Request < Rack::Request HEADER_PARAM = /\s*[\w.]+=(?:[\w.]+|"(?:[^"\\]|\\.)*")?\s*/.freeze HEADER_VALUE_WITH_PARAMS = %r{(?:(?:\w+|\*)/(?:\w+(?:\.|-|\+)?|\*)*)\s*(?:;#{HEADER_PARAM})*}.freeze # Returns an array of acceptable media types for the response def accept @env['sinatra.accept'] ||= if @env.include?('HTTP_ACCEPT') && (@env['HTTP_ACCEPT'].to_s != '') @env['HTTP_ACCEPT'] .to_s .scan(HEADER_VALUE_WITH_PARAMS) .map! { |e| AcceptEntry.new(e) } .sort else [AcceptEntry.new('*/*')] end end def accept?(type) preferred_type(type).to_s.include?(type) end def preferred_type(*types) return accept.first if types.empty? types.flatten! return types.first if accept.empty? accept.detect do |accept_header| type = types.detect { |t| MimeTypeEntry.new(t).accepts?(accept_header) } return type if type end end alias secure? ssl? def forwarded? !forwarded_authority.nil? end def safe? get? || head? || options? || trace? end def idempotent? safe? || put? || delete? || link? || unlink? end def link? request_method == 'LINK' end def unlink? request_method == 'UNLINK' end def params super rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e raise BadRequest, "Invalid query parameters: #{Rack::Utils.escape_html(e.message)}" rescue EOFError => e raise BadRequest, "Invalid multipart/form-data: #{Rack::Utils.escape_html(e.message)}" end class AcceptEntry attr_accessor :params attr_reader :entry def initialize(entry) params = entry.scan(HEADER_PARAM).map! do |s| key, value = s.strip.split('=', 2) value = value[1..-2].gsub(/\\(.)/, '\1') if value.start_with?('"') [key, value] end @entry = entry @type = entry[/[^;]+/].delete(' ') @params = params.to_h @q = @params.delete('q') { 1.0 }.to_f end def <=>(other) other.priority <=> priority end def priority # We sort in descending order; better matches should be higher. [@q, -@type.count('*'), @params.size] end def to_str @type end def to_s(full = false) full ? entry : to_str end def respond_to?(*args) super || to_str.respond_to?(*args) end def method_missing(*args, &block) to_str.send(*args, &block) end end class MimeTypeEntry attr_reader :params def initialize(entry) params = entry.scan(HEADER_PARAM).map! do |s| key, value = s.strip.split('=', 2) value = value[1..-2].gsub(/\\(.)/, '\1') if value.start_with?('"') [key, value] end @type = entry[/[^;]+/].delete(' ') @params = params.to_h end def accepts?(entry) File.fnmatch(entry, self) && matches_params?(entry.params) end def to_str @type end def matches_params?(params) return true if @params.empty? params.all? { |k, v| !@params.key?(k) || @params[k] == v } end end end # The response object. See Rack::Response and Rack::Response::Helpers for # more info: # https://rubydoc.info/github/rack/rack/main/Rack/Response # https://rubydoc.info/github/rack/rack/main/Rack/Response/Helpers class Response < Rack::Response DROP_BODY_RESPONSES = [204, 304].freeze def body=(value) value = value.body while Rack::Response === value @body = String === value ? [value.to_str] : value end def each block_given? ? super : enum_for(:each) end def finish result = body if drop_content_info? headers.delete 'content-length' headers.delete 'content-type' end if drop_body? close result = [] end if calculate_content_length? # if some other code has already set content-length, don't muck with it # currently, this would be the static file-handler headers['content-length'] = body.map(&:bytesize).reduce(0, :+).to_s end [status, headers, result] end private def calculate_content_length? headers['content-type'] && !headers['content-length'] && (Array === body) end def drop_content_info? informational? || drop_body? end def drop_body? DROP_BODY_RESPONSES.include?(status) end end # Some Rack handlers implement an extended body object protocol, however, # some middleware (namely Rack::Lint) will break it by not mirroring the methods in question. # This middleware will detect an extended body object and will make sure it reaches the # handler directly. We do this here, so our middleware and middleware set up by the app will # still be able to run. class ExtendedRack < Struct.new(:app) def call(env) result = app.call(env) callback = env['async.callback'] return result unless callback && async?(*result) after_response { callback.call result } setup_close(env, *result) throw :async end private def setup_close(env, _status, _headers, body) return unless body.respond_to?(:close) && env.include?('async.close') env['async.close'].callback { body.close } env['async.close'].errback { body.close } end def after_response(&block) raise NotImplementedError, 'only supports EventMachine at the moment' unless defined? EventMachine EventMachine.next_tick(&block) end def async?(status, _headers, body) return true if status == -1 body.respond_to?(:callback) && body.respond_to?(:errback) end end # Behaves exactly like Rack::CommonLogger with the notable exception that it does nothing, # if another CommonLogger is already in the middleware chain. class CommonLogger < Rack::CommonLogger def call(env) env['sinatra.commonlogger'] ? @app.call(env) : super end superclass.class_eval do alias_method :call_without_check, :call unless method_defined? :call_without_check def call(env) env['sinatra.commonlogger'] = true call_without_check(env) end end end class Error < StandardError # :nodoc: end class BadRequest < Error # :nodoc: def http_status; 400 end end class NotFound < Error # :nodoc: def http_status; 404 end end # Methods available to routes, before/after filters, and views. module Helpers # Set or retrieve the response status code. def status(value = nil) response.status = Rack::Utils.status_code(value) if value response.status end # Set or retrieve the response body. When a block is given, # evaluation is deferred until the body is read with #each. def body(value = nil, &block) if block_given? def block.each; yield(call) end response.body = block elsif value unless request.head? || value.is_a?(Rack::Files::BaseIterator) || value.is_a?(Stream) headers.delete 'content-length' end response.body = value else response.body end end # Halt processing and redirect to the URI provided. def redirect(uri, *args) # SERVER_PROTOCOL is required in Rack 3, fall back to HTTP_VERSION # for servers not updated for Rack 3 (like Puma 5) http_version = env['SERVER_PROTOCOL'] || env['HTTP_VERSION'] if (http_version == 'HTTP/1.1') && (env['REQUEST_METHOD'] != 'GET') status 303 else status 302 end # According to RFC 2616 section 14.30, "the field value consists of a # single absolute URI" response['Location'] = uri(uri.to_s, settings.absolute_redirects?, settings.prefixed_redirects?) halt(*args) end # Generates the absolute URI for a given path in the app. # Takes Rack routers and reverse proxies into account. def uri(addr = nil, absolute = true, add_script_name = true) return addr if addr.to_s =~ /\A[a-z][a-z0-9+.\-]*:/i uri = [host = String.new] if absolute host << "http#{'s' if request.secure?}://" host << if request.forwarded? || (request.port != (request.secure? ? 443 : 80)) request.host_with_port else request.host end end uri << request.script_name.to_s if add_script_name uri << (addr || request.path_info).to_s File.join uri end alias url uri alias to uri # Halt processing and return the error status provided. def error(code, body = nil) if code.respond_to? :to_str body = code.to_str code = 500 end response.body = body unless body.nil? halt code end # Halt processing and return a 404 Not Found. def not_found(body = nil) error 404, body end # Set multiple response headers with Hash. def headers(hash = nil) response.headers.merge! hash if hash response.headers end # Access the underlying Rack session. def session request.session end # Access shared logger object. def logger request.logger end # Look up a media type by file extension in Rack's mime registry. def mime_type(type) Base.mime_type(type) end # Set the content-type of the response body given a media type or file # extension. def content_type(type = nil, params = {}) return response['content-type'] unless type default = params.delete :default mime_type = mime_type(type) || default raise format('Unknown media type: %p', type) if mime_type.nil? mime_type = mime_type.dup unless params.include?(:charset) || settings.add_charset.all? { |p| !(p === mime_type) } params[:charset] = params.delete('charset') || settings.default_encoding end params.delete :charset if mime_type.include? 'charset' unless params.empty? mime_type << ';' mime_type << params.map do |key, val| val = val.inspect if val.to_s =~ /[";,]/ "#{key}=#{val}" end.join(';') end response['content-type'] = mime_type end # https://html.spec.whatwg.org/#multipart-form-data MULTIPART_FORM_DATA_REPLACEMENT_TABLE = { '"' => '%22', "\r" => '%0D', "\n" => '%0A' }.freeze # Set the Content-Disposition to "attachment" with the specified filename, # instructing the user agents to prompt to save. def attachment(filename = nil, disposition = :attachment) response['Content-Disposition'] = disposition.to_s.dup return unless filename params = format('; filename="%s"', File.basename(filename).gsub(/["\r\n]/, MULTIPART_FORM_DATA_REPLACEMENT_TABLE)) response['Content-Disposition'] << params ext = File.extname(filename) content_type(ext) unless response['content-type'] || ext.empty? end # Use the contents of the file at +path+ as the response body. def send_file(path, opts = {}) if opts[:type] || !response['content-type'] content_type opts[:type] || File.extname(path), default: 'application/octet-stream' end disposition = opts[:disposition] filename = opts[:filename] disposition = :attachment if disposition.nil? && filename filename = path if filename.nil? attachment(filename, disposition) if disposition last_modified opts[:last_modified] if opts[:last_modified] file = Rack::Files.new(File.dirname(settings.app_file)) result = file.serving(request, path) result[1].each { |k, v| headers[k] ||= v } headers['content-length'] = result[1]['content-length'] opts[:status] &&= Integer(opts[:status]) halt (opts[:status] || result[0]), result[2] rescue Errno::ENOENT not_found end # Class of the response body in case you use #stream. # # Three things really matter: The front and back block (back being the # block generating content, front the one sending it to the client) and # the scheduler, integrating with whatever concurrency feature the Rack # handler is using. # # Scheduler has to respond to defer and schedule. class Stream def self.schedule(*) yield end def self.defer(*) yield end def initialize(scheduler = self.class, keep_open = false, &back) @back = back.to_proc @scheduler = scheduler @keep_open = keep_open @callbacks = [] @closed = false end def close return if closed? @closed = true @scheduler.schedule { @callbacks.each { |c| c.call } } end def each(&front) @front = front @scheduler.defer do begin @back.call(self) rescue Exception => e @scheduler.schedule { raise e } ensure close unless @keep_open end end end def <<(data) @scheduler.schedule { @front.call(data.to_s) } self end def callback(&block) return yield if closed? @callbacks << block end alias errback callback def closed? @closed end end # Allows to start sending data to the client even though later parts of # the response body have not yet been generated. # # The close parameter specifies whether Stream#close should be called # after the block has been executed. def stream(keep_open = false) scheduler = env['async.callback'] ? EventMachine : Stream current = @params.dup stream = if scheduler == Stream && keep_open Stream.new(scheduler, false) do |out| until out.closed? with_params(current) { yield(out) } end end else Stream.new(scheduler, keep_open) { |out| with_params(current) { yield(out) } } end body stream end # Specify response freshness policy for HTTP caches (Cache-Control header). # Any number of non-value directives (:public, :private, :no_cache, # :no_store, :must_revalidate, :proxy_revalidate) may be passed along with # a Hash of value directives (:max_age, :s_maxage). # # cache_control :public, :must_revalidate, :max_age => 60 # => Cache-Control: public, must-revalidate, max-age=60 # # See RFC 2616 / 14.9 for more on standard cache control directives: # http://tools.ietf.org/html/rfc2616#section-14.9.1 def cache_control(*values) if values.last.is_a?(Hash) hash = values.pop hash.reject! { |_k, v| v == false } hash.reject! { |k, v| values << k if v == true } else hash = {} end values.map! { |value| value.to_s.tr('_', '-') } hash.each do |key, value| key = key.to_s.tr('_', '-') value = value.to_i if %w[max-age s-maxage].include? key values << "#{key}=#{value}" end response['Cache-Control'] = values.join(', ') if values.any? end # Set the Expires header and Cache-Control/max-age directive. Amount # can be an integer number of seconds in the future or a Time object # indicating when the response should be considered "stale". The remaining # "values" arguments are passed to the #cache_control helper: # # expires 500, :public, :must_revalidate # => Cache-Control: public, must-revalidate, max-age=500 # => Expires: Mon, 08 Jun 2009 08:50:17 GMT # def expires(amount, *values) values << {} unless values.last.is_a?(Hash) if amount.is_a? Integer time = Time.now + amount.to_i max_age = amount else time = time_for amount max_age = time - Time.now end values.last.merge!(max_age: max_age) { |_key, v1, v2| v1 || v2 } cache_control(*values) response['Expires'] = time.httpdate end # Set the last modified time of the resource (HTTP 'Last-Modified' header) # and halt if conditional GET matches. The +time+ argument is a Time, # DateTime, or other object that responds to +to_time+. # # When the current request includes an 'If-Modified-Since' header that is # equal or later than the time specified, execution is immediately halted # with a '304 Not Modified' response. def last_modified(time) return unless time time = time_for time response['Last-Modified'] = time.httpdate return if env['HTTP_IF_NONE_MATCH'] if (status == 200) && env['HTTP_IF_MODIFIED_SINCE'] # compare based on seconds since epoch since = Time.httpdate(env['HTTP_IF_MODIFIED_SINCE']).to_i halt 304 if since >= time.to_i end if (success? || (status == 412)) && env['HTTP_IF_UNMODIFIED_SINCE'] # compare based on seconds since epoch since = Time.httpdate(env['HTTP_IF_UNMODIFIED_SINCE']).to_i halt 412 if since < time.to_i end rescue ArgumentError end ETAG_KINDS = %i[strong weak].freeze # Set the response entity tag (HTTP 'ETag' header) and halt if conditional # GET matches. The +value+ argument is an identifier that uniquely # identifies the current version of the resource. The +kind+ argument # indicates whether the etag should be used as a :strong (default) or :weak # cache validator. # # When the current request includes an 'If-None-Match' header with a # matching etag, execution is immediately halted. If the request method is # GET or HEAD, a '304 Not Modified' response is sent. def etag(value, options = {}) # Before touching this code, please double check RFC 2616 14.24 and 14.26. options = { kind: options } unless Hash === options kind = options[:kind] || :strong new_resource = options.fetch(:new_resource) { request.post? } unless ETAG_KINDS.include?(kind) raise ArgumentError, ':strong or :weak expected' end value = format('"%s"', value) value = "W/#{value}" if kind == :weak response['ETag'] = value return unless success? || status == 304 if etag_matches?(env['HTTP_IF_NONE_MATCH'], new_resource) halt(request.safe? ? 304 : 412) end if env['HTTP_IF_MATCH'] return if etag_matches?(env['HTTP_IF_MATCH'], new_resource) halt 412 end nil end # Sugar for redirect (example: redirect back) def back request.referer end # whether or not the status is set to 1xx def informational? status.between? 100, 199 end # whether or not the status is set to 2xx def success? status.between? 200, 299 end # whether or not the status is set to 3xx def redirect? status.between? 300, 399 end # whether or not the status is set to 4xx def client_error? status.between? 400, 499 end # whether or not the status is set to 5xx def server_error? status.between? 500, 599 end # whether or not the status is set to 404 def not_found? status == 404 end # whether or not the status is set to 400 def bad_request? status == 400 end # Generates a Time object from the given value. # Used by #expires and #last_modified. def time_for(value) if value.is_a? Numeric Time.at value elsif value.respond_to? :to_s Time.parse value.to_s else value.to_time end rescue ArgumentError => e raise e rescue Exception raise ArgumentError, "unable to convert #{value.inspect} to a Time object" end private # Helper method checking if a ETag value list includes the current ETag. def etag_matches?(list, new_resource = request.post?) return !new_resource if list == '*' list.to_s.split(',').map(&:strip).include?(response['ETag']) end def with_params(temp_params) original = @params @params = temp_params yield ensure @params = original if original end end # Template rendering methods. Each method takes the name of a template # to render as a Symbol and returns a String with the rendered output, # as well as an optional hash with additional options. # # `template` is either the name or path of the template as symbol # (Use `:'subdir/myview'` for views in subdirectories), or a string # that will be rendered. # # Possible options are: # :content_type The content type to use, same arguments as content_type. # :layout If set to something falsy, no layout is rendered, otherwise # the specified layout is used (Ignored for `sass`) # :layout_engine Engine to use for rendering the layout. # :locals A hash with local variables that should be available # in the template # :scope If set, template is evaluate with the binding of the given # object rather than the application instance. # :views Views directory to use. module Templates module ContentTyped attr_accessor :content_type end def initialize super @default_layout = :layout @preferred_extension = nil end def erb(template, options = {}, locals = {}, &block) render(:erb, template, options, locals, &block) end def haml(template, options = {}, locals = {}, &block) render(:haml, template, options, locals, &block) end def sass(template, options = {}, locals = {}) options[:default_content_type] = :css options[:exclude_outvar] = true options[:layout] = nil render :sass, template, options, locals end def scss(template, options = {}, locals = {}) options[:default_content_type] = :css options[:exclude_outvar] = true options[:layout] = nil render :scss, template, options, locals end def builder(template = nil, options = {}, locals = {}, &block) options[:default_content_type] = :xml render_ruby(:builder, template, options, locals, &block) end def liquid(template, options = {}, locals = {}, &block) render(:liquid, template, options, locals, &block) end def markdown(template, options = {}, locals = {}) options[:exclude_outvar] = true render :markdown, template, options, locals end def rdoc(template, options = {}, locals = {}) render :rdoc, template, options, locals end def asciidoc(template, options = {}, locals = {}) render :asciidoc, template, options, locals end def markaby(template = nil, options = {}, locals = {}, &block) render_ruby(:mab, template, options, locals, &block) end def nokogiri(template = nil, options = {}, locals = {}, &block) options[:default_content_type] = :xml render_ruby(:nokogiri, template, options, locals, &block) end def slim(template, options = {}, locals = {}, &block) render(:slim, template, options, locals, &block) end def yajl(template, options = {}, locals = {}) options[:default_content_type] = :json render :yajl, template, options, locals end def rabl(template, options = {}, locals = {}) Rabl.register! render :rabl, template, options, locals end # Calls the given block for every possible template file in views, # named name.ext, where ext is registered on engine. def find_template(views, name, engine) yield ::File.join(views, "#{name}.#{@preferred_extension}") Tilt.default_mapping.extensions_for(engine).each do |ext| yield ::File.join(views, "#{name}.#{ext}") unless ext == @preferred_extension end end private # logic shared between builder and nokogiri def render_ruby(engine, template, options = {}, locals = {}, &block) if template.is_a?(Hash) options = template template = nil end template = proc { block } if template.nil? render engine, template, options, locals end def render(engine, data, options = {}, locals = {}, &block) # merge app-level options engine_options = settings.respond_to?(engine) ? settings.send(engine) : {} options.merge!(engine_options) { |_key, v1, _v2| v1 } # extract generic options locals = options.delete(:locals) || locals || {} views = options.delete(:views) || settings.views || './views' layout = options[:layout] layout = false if layout.nil? && options.include?(:layout) eat_errors = layout.nil? layout = engine_options[:layout] if layout.nil? || (layout == true && engine_options[:layout] != false) layout = @default_layout if layout.nil? || (layout == true) layout_options = options.delete(:layout_options) || {} content_type = options.delete(:default_content_type) content_type = options.delete(:content_type) || content_type layout_engine = options.delete(:layout_engine) || engine scope = options.delete(:scope) || self exclude_outvar = options.delete(:exclude_outvar) options.delete(:layout) # set some defaults options[:outvar] ||= '@_out_buf' unless exclude_outvar options[:default_encoding] ||= settings.default_encoding # compile and render template begin layout_was = @default_layout @default_layout = false template = compile_template(engine, data, options, views) output = template.render(scope, locals, &block) ensure @default_layout = layout_was end # render layout if layout extra_options = { views: views, layout: false, eat_errors: eat_errors, scope: scope } options = options.merge(extra_options).merge!(layout_options) catch(:layout_missing) { return render(layout_engine, layout, options, locals) { output } } end if content_type # sass-embedded returns a frozen string output = +output output.extend(ContentTyped).content_type = content_type end output end def compile_template(engine, data, options, views) eat_errors = options.delete :eat_errors template = Tilt[engine] raise "Template engine not found: #{engine}" if template.nil? case data when Symbol template_cache.fetch engine, data, options, views do body, path, line = settings.templates[data] if body body = body.call if body.respond_to?(:call) template.new(path, line.to_i, options) { body } else found = false @preferred_extension = engine.to_s find_template(views, data, template) do |file| path ||= file # keep the initial path rather than the last one found = File.exist?(file) if found path = file break end end throw :layout_missing if eat_errors && !found template.new(path, 1, options) end end when Proc compile_block_template(template, options, &data) when String template_cache.fetch engine, data, options, views do compile_block_template(template, options) { data } end else raise ArgumentError, "Sorry, don't know how to render #{data.inspect}." end end def compile_block_template(template, options, &body) first_location = caller_locations.first path = first_location.path line = first_location.lineno path = options[:path] || path line = options[:line] || line template.new(path, line.to_i, options, &body) end end # Extremely simple template cache implementation. # * Not thread-safe. # * Size is unbounded. # * Keys are not copied defensively, and should not be modified after # being passed to #fetch. More specifically, the values returned by # key#hash and key#eql? should not change. # # Implementation copied from Tilt::Cache. class TemplateCache def initialize @cache = {} end # Caches a value for key, or returns the previously cached value. # If a value has been previously cached for key then it is # returned. Otherwise, block is yielded to and its return value # which may be nil, is cached under key and returned. def fetch(*key) @cache.fetch(key) do @cache[key] = yield end end # Clears the cache. def clear @cache = {} end end # Base class for all Sinatra applications and middleware. class Base include Rack::Utils include Helpers include Templates URI_INSTANCE = defined?(URI::RFC2396_PARSER) ? URI::RFC2396_PARSER : URI::RFC2396_Parser.new attr_accessor :app, :env, :request, :response, :params attr_reader :template_cache def initialize(app = nil, **_kwargs) super() @app = app @template_cache = TemplateCache.new @pinned_response = nil # whether a before! filter pinned the content-type yield self if block_given? end # Rack call interface. def call(env) dup.call!(env) end def call!(env) # :nodoc: @env = env @params = IndifferentHash.new @request = Request.new(env) @response = Response.new @pinned_response = nil template_cache.clear if settings.reload_templates invoke { dispatch! } invoke { error_block!(response.status) } unless @env['sinatra.error'] unless @response['content-type'] if Array === body && body[0].respond_to?(:content_type) content_type body[0].content_type elsif (default = settings.default_content_type) content_type default end end @response.finish end # Access settings defined with Base.set. def self.settings self end # Access settings defined with Base.set. def settings self.class.settings end # Exit the current block, halts any further processing # of the request, and returns the specified response. def halt(*response) response = response.first if response.length == 1 throw :halt, response end # Pass control to the next matching route. # If there are no more matching routes, Sinatra will # return a 404 response. def pass(&block) throw :pass, block end # Forward the request to the downstream app -- middleware only. def forward raise 'downstream app not set' unless @app.respond_to? :call status, headers, body = @app.call env @response.status = status @response.body = body @response.headers.merge! headers nil end private # Run filters defined on the class and all superclasses. # Accepts an optional block to call after each filter is applied. def filter!(type, base = settings, &block) filter!(type, base.superclass, &block) if base.superclass.respond_to?(:filters) base.filters[type].each do |args| result = process_route(*args) block.call(result) if block_given? end end # Run routes defined on the class and all superclasses. def route!(base = settings, pass_block = nil) routes = base.routes[@request.request_method] routes&.each do |pattern, conditions, block| response.delete_header('content-type') unless @pinned_response
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
true
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/lib/sinatra/indifferent_hash.rb
lib/sinatra/indifferent_hash.rb
# frozen_string_literal: true module Sinatra # A poor man's ActiveSupport::HashWithIndifferentAccess, with all the Rails-y # stuff removed. # # Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are # considered to be the same. # # rgb = Sinatra::IndifferentHash.new # # rgb[:black] = '#000000' # symbol assignment # rgb[:black] # => '#000000' # symbol retrieval # rgb['black'] # => '#000000' # string retrieval # # rgb['white'] = '#FFFFFF' # string assignment # rgb[:white] # => '#FFFFFF' # symbol retrieval # rgb['white'] # => '#FFFFFF' # string retrieval # # Internally, symbols are mapped to strings when used as keys in the entire # writing interface (calling e.g. <tt>[]=</tt>, <tt>merge</tt>). This mapping # belongs to the public interface. For example, given: # # hash = Sinatra::IndifferentHash.new # hash[:a] = 1 # # You are guaranteed that the key is returned as a string: # # hash.keys # => ["a"] # # Technically other types of keys are accepted: # # hash = Sinatra::IndifferentHash # hash[:a] = 1 # hash[0] = 0 # hash # => { "a"=>1, 0=>0 } # # But this class is intended for use cases where strings or symbols are the # expected keys and it is convenient to understand both as the same. For # example the +params+ hash in Sinatra. class IndifferentHash < Hash def self.[](*args) new.merge!(Hash[*args]) end def default(*args) args.map!(&method(:convert_key)) super(*args) end def default=(value) super(convert_value(value)) end def assoc(key) super(convert_key(key)) end def rassoc(value) super(convert_value(value)) end def fetch(key, *args) args.map!(&method(:convert_value)) super(convert_key(key), *args) end def [](key) super(convert_key(key)) end def []=(key, value) super(convert_key(key), convert_value(value)) end alias store []= def key(value) super(convert_value(value)) end def key?(key) super(convert_key(key)) end alias has_key? key? alias include? key? alias member? key? def value?(value) super(convert_value(value)) end alias has_value? value? def delete(key) super(convert_key(key)) end # Added in Ruby 2.3 def dig(key, *other_keys) super(convert_key(key), *other_keys) end def fetch_values(*keys) keys.map!(&method(:convert_key)) super(*keys) end def slice(*keys) keys.map!(&method(:convert_key)) self.class[super(*keys)] end def values_at(*keys) keys.map!(&method(:convert_key)) super(*keys) end def merge!(*other_hashes) other_hashes.each do |other_hash| if other_hash.is_a?(self.class) super(other_hash) else other_hash.each_pair do |key, value| key = convert_key(key) value = yield(key, self[key], value) if block_given? && key?(key) self[key] = convert_value(value) end end end self end alias update merge! def merge(*other_hashes, &block) dup.merge!(*other_hashes, &block) end def replace(other_hash) super(other_hash.is_a?(self.class) ? other_hash : self.class[other_hash]) end def transform_values(&block) dup.transform_values!(&block) end def transform_values! super super(&method(:convert_value)) end def transform_keys(&block) dup.transform_keys!(&block) end def transform_keys! super super(&method(:convert_key)) end def select(*args, &block) return to_enum(:select) unless block_given? dup.tap { |hash| hash.select!(*args, &block) } end def reject(*args, &block) return to_enum(:reject) unless block_given? dup.tap { |hash| hash.reject!(*args, &block) } end def compact dup.tap(&:compact!) end def except(*keys) keys.map!(&method(:convert_key)) self.class[super(*keys)] end if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("3.0") private def convert_key(key) key.is_a?(Symbol) ? key.to_s : key end def convert_value(value) case value when Hash value.is_a?(self.class) ? value : self.class[value] when Array value.map(&method(:convert_value)) else value end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/lib/sinatra/show_exceptions.rb
lib/sinatra/show_exceptions.rb
# frozen_string_literal: true require 'rack/show_exceptions' module Sinatra # Sinatra::ShowExceptions catches all exceptions raised from the app it # wraps. It shows a useful backtrace with the sourcefile and clickable # context, the whole Rack environment and the request data. # # Be careful when you use this on public-facing sites as it could reveal # information helpful to attackers. class ShowExceptions < Rack::ShowExceptions @@eats_errors = Object.new def @@eats_errors.flush(*) end def @@eats_errors.puts(*) end def initialize(app) @app = app end def call(env) @app.call(env) rescue Exception => e errors = env['rack.errors'] env['rack.errors'] = @@eats_errors if prefers_plain_text?(env) content_type = 'text/plain' body = dump_exception(e) else content_type = 'text/html' body = pretty(env, e) end env['rack.errors'] = errors [ 500, { 'content-type' => content_type, 'content-length' => body.bytesize.to_s }, [body] ] end def template TEMPLATE end private def bad_request?(exception) Sinatra::BadRequest === exception end def prefers_plain_text?(env) Request.new(env).preferred_type('text/plain', 'text/html') != 'text/html' && [/curl/].index { |item| item =~ env['HTTP_USER_AGENT'] } end def frame_class(frame) if frame.filename =~ %r{lib/sinatra.*\.rb} 'framework' elsif (defined?(Gem) && frame.filename.include?(Gem.dir)) || frame.filename =~ %r{/bin/(\w+)\z} 'system' else 'app' end end TEMPLATE = ERB.new <<-HTML # :nodoc: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title><%=h exception.class %> at <%=h path %></title> <script type="text/javascript"> //<!-- function toggle(id) { var pre = document.getElementById("pre-" + id); var post = document.getElementById("post-" + id); var context = document.getElementById("context-" + id); if (pre.style.display == 'block') { pre.style.display = 'none'; post.style.display = 'none'; context.style.background = "none"; } else { pre.style.display = 'block'; post.style.display = 'block'; context.style.background = "#fffed9"; } } function toggleBacktrace(){ var bt = document.getElementById("backtrace"); var toggler = document.getElementById("expando"); if (bt.className == 'condensed') { bt.className = 'expanded'; toggler.innerHTML = "(condense)"; } else { bt.className = 'condensed'; toggler.innerHTML = "(expand)"; } } //--> </script> <style type="text/css" media="screen"> * {margin: 0; padding: 0; border: 0; outline: 0;} div.clear {clear: both;} body {background: #EEEEEE; margin: 0; padding: 0; font-family: 'Lucida Grande', 'Lucida Sans Unicode', 'Garuda';} code {font-family: 'Lucida Console', monospace; font-size: 12px;} li {height: 18px;} ul {list-style: none; margin: 0; padding: 0;} ol:hover {cursor: pointer;} ol li {white-space: pre;} #explanation {font-size: 12px; color: #666666; margin: 20px 0 0 100px;} /* WRAP */ #wrap {width: 1000px; background: #FFFFFF; margin: 0 auto; padding: 30px 50px 20px 50px; border-left: 1px solid #DDDDDD; border-right: 1px solid #DDDDDD;} /* HEADER */ #header {margin: 0 auto 25px auto;} #header img {float: left;} #header #summary {float: left; margin: 12px 0 0 20px; width:660px; font-family: 'Lucida Grande', 'Lucida Sans Unicode';} h1 {margin: 0; font-size: 36px; color: #981919;} h2 {margin: 0; font-size: 22px; color: #333333;} #header ul {margin: 0; font-size: 12px; color: #666666;} #header ul li strong{color: #444444;} #header ul li {display: inline; padding: 0 10px;} #header ul li.first {padding-left: 0;} #header ul li.last {border: 0; padding-right: 0;} /* BODY */ #backtrace, #get, #post, #cookies, #rack {width: 980px; margin: 0 auto 10px auto;} p#nav {float: right; font-size: 14px;} /* BACKTRACE */ a#expando {float: left; padding-left: 5px; color: #666666; font-size: 14px; text-decoration: none; cursor: pointer;} a#expando:hover {text-decoration: underline;} h3 {float: left; width: 100px; margin-bottom: 10px; color: #981919; font-size: 14px; font-weight: bold;} #nav a {color: #666666; text-decoration: none; padding: 0 5px;} #backtrace li.frame-info {background: #f7f7f7; padding-left: 10px; font-size: 12px; color: #333333;} #backtrace ul {list-style-position: outside; border: 1px solid #E9E9E9; border-bottom: 0;} #backtrace ol {width: 920px; margin-left: 50px; font: 10px 'Lucida Console', monospace; color: #666666;} #backtrace ol li {border: 0; border-left: 1px solid #E9E9E9; padding: 2px 0;} #backtrace ol code {font-size: 10px; color: #555555; padding-left: 5px;} #backtrace-ul li {border-bottom: 1px solid #E9E9E9; height: auto; padding: 3px 0;} #backtrace-ul .code {padding: 6px 0 4px 0;} #backtrace.condensed .system, #backtrace.condensed .framework {display:none;} /* REQUEST DATA */ p.no-data {padding-top: 2px; font-size: 12px; color: #666666;} table.req {width: 980px; text-align: left; font-size: 12px; color: #666666; padding: 0; border-spacing: 0; border: 1px solid #EEEEEE; border-bottom: 0; border-left: 0; clear:both} table.req tr th {padding: 2px 10px; font-weight: bold; background: #F7F7F7; border-bottom: 1px solid #EEEEEE; border-left: 1px solid #EEEEEE;} table.req tr td {padding: 2px 20px 2px 10px; border-bottom: 1px solid #EEEEEE; border-left: 1px solid #EEEEEE;} /* HIDE PRE/POST CODE AT START */ .pre-context, .post-context {display: none;} table td.code {width:750px} table td.code div {width:750px;overflow:hidden} </style> </head> <body> <div id="wrap"> <div id="header"> <img src="<%= env['SCRIPT_NAME'] %>/__sinatra__/500.png" alt="application error" height="161" width="313" /> <div id="summary"> <h1><strong><%=h exception.class %></strong> at <strong><%=h path %> </strong></h1> <h2><%=h exception.message %></h2> <ul> <li class="first"><strong>file:</strong> <code> <%=h frames.first.filename.split("/").last %></code></li> <li><strong>location:</strong> <code><%=h frames.first.function %> </code></li> <li class="last"><strong>line: </strong> <%=h frames.first.lineno %></li> </ul> </div> <div class="clear"></div> </div> <div id="backtrace" class='condensed'> <h3>BACKTRACE</h3> <p><a href="#" id="expando" onclick="toggleBacktrace(); return false">(expand)</a></p> <p id="nav"><strong>JUMP TO:</strong> <% unless bad_request?(exception) %> <a href="#get-info">GET</a> <a href="#post-info">POST</a> <% end %> <a href="#cookie-info">COOKIES</a> <a href="#env-info">ENV</a> </p> <div class="clear"></div> <ul id="backtrace-ul"> <% id = 1 %> <% frames.each do |frame| %> <% if frame.context_line && frame.context_line != "#" %> <li class="frame-info <%= frame_class(frame) %>"> <code><%=h frame.filename %></code> in <code><strong><%=h frame.function %></strong></code> </li> <li class="code <%= frame_class(frame) %>"> <% if frame.pre_context %> <ol start="<%=h frame.pre_context_lineno + 1 %>" class="pre-context" id="pre-<%= id %>" onclick="toggle(<%= id %>);"> <% frame.pre_context.each do |line| %> <li class="pre-context-line"><code><%=h line %></code></li> <% end %> </ol> <% end %> <ol start="<%= frame.lineno %>" class="context" id="<%= id %>" onclick="toggle(<%= id %>);"> <li class="context-line" id="context-<%= id %>"><code><%= h frame.context_line %></code></li> </ol> <% if frame.post_context %> <ol start="<%=h frame.lineno + 1 %>" class="post-context" id="post-<%= id %>" onclick="toggle(<%= id %>);"> <% frame.post_context.each do |line| %> <li class="post-context-line"><code><%=h line %></code></li> <% end %> </ol> <% end %> <div class="clear"></div> </li> <% end %> <% id += 1 %> <% end %> </ul> </div> <!-- /BACKTRACE --> <% unless bad_request?(exception) %> <div id="get"> <h3 id="get-info">GET</h3> <% if req.GET and not req.GET.empty? %> <table class="req"> <tr> <th>Variable</th> <th>Value</th> </tr> <% req.GET.sort_by { |k, v| k.to_s }.each { |key, val| %> <tr> <td><%=h key %></td> <td class="code"><div><%=h val.inspect %></div></td> </tr> <% } %> </table> <% else %> <p class="no-data">No GET data.</p> <% end %> <div class="clear"></div> </div> <!-- /GET --> <div id="post"> <h3 id="post-info">POST</h3> <% if req.POST and not req.POST.empty? %> <table class="req"> <tr> <th>Variable</th> <th>Value</th> </tr> <% req.POST.sort_by { |k, v| k.to_s }.each { |key, val| %> <tr> <td><%=h key %></td> <td class="code"><div><%=h val.inspect %></div></td> </tr> <% } %> </table> <% else %> <p class="no-data">No POST data.</p> <% end %> <div class="clear"></div> </div> <!-- /POST --> <% end %> <div id="cookies"> <h3 id="cookie-info">COOKIES</h3> <% unless req.cookies.empty? %> <table class="req"> <tr> <th>Variable</th> <th>Value</th> </tr> <% req.cookies.each { |key, val| %> <tr> <td><%=h key %></td> <td class="code"><div><%=h val.inspect %></div></td> </tr> <% } %> </table> <% else %> <p class="no-data">No cookie data.</p> <% end %> <div class="clear"></div> </div> <!-- /COOKIES --> <div id="rack"> <h3 id="env-info">Rack ENV</h3> <table class="req"> <tr> <th>Variable</th> <th>Value</th> </tr> <% env.sort_by { |k, v| k.to_s }.each { |key, val| %> <tr> <td><%=h key %></td> <td class="code"><div><%=h val %></div></td> </tr> <% } %> </table> <div class="clear"></div> </div> <!-- /RACK ENV --> <p id="explanation">You're seeing this error because you have enabled the <code>show_exceptions</code> setting.</p> </div> <!-- /WRAP --> </body> </html> HTML end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/lib/sinatra/middleware/logger.rb
lib/sinatra/middleware/logger.rb
# frozen_string_literal: true require 'logger' module Sinatra module Middleware class Logger def initialize(app, level = ::Logger::INFO) @app, @level = app, level end def call(env) logger = ::Logger.new(env[Rack::RACK_ERRORS]) logger.level = @level env[Rack::RACK_LOGGER] = logger @app.call(env) end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/custom_logger_spec.rb
sinatra-contrib/spec/custom_logger_spec.rb
require 'spec_helper' require 'sinatra/custom_logger' RSpec.describe Sinatra::CustomLogger do before do rack_logger = @rack_logger = double mock_app do helpers Sinatra::CustomLogger before do env['rack.logger'] = rack_logger end get '/' do logger.info 'Logged message' 'Response' end end end describe '#logger' do it 'falls back to request.logger' do expect(@rack_logger).to receive(:info).with('Logged message') get '/' end context 'logger setting is set' do before do custom_logger = @custom_logger = double @app.class_eval do configure do set :logger, custom_logger end end end it 'calls custom logger' do expect(@custom_logger).to receive(:info).with('Logged message') get '/' end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/content_for_spec.rb
sinatra-contrib/spec/content_for_spec.rb
require 'spec_helper' RSpec.describe Sinatra::ContentFor do subject do Sinatra.new do helpers Sinatra::ContentFor set :views, File.expand_path("content_for", __dir__) end.new! end Tilt.prefer Tilt::ERBTemplate require 'hamlit' Tilt.register Tilt::HamlTemplate, :haml extend Forwardable def_delegators :subject, :content_for, :clear_content_for, :yield_content def render(engine, template) subject.send(:render, engine, template, :layout => false).gsub(/\s/, '') end describe "without templates" do it 'renders blocks declared with the same key you use when rendering' do content_for(:foo) { "foo" } expect(yield_content(:foo)).to eq("foo") end it 'renders blocks more than once' do content_for(:foo) { "foo" } 3.times { expect(yield_content(:foo)).to eq("foo") } end it 'does not render a block with a different key' do content_for(:bar) { "bar" } expect(yield_content(:foo)).to be_empty end it 'renders default content if no block matches the key and a default block is specified' do expect(yield_content(:foo) {}).to be_nil expect(yield_content(:foo) { "foo" }).to eq("foo") end it 'renders multiple blocks with the same key' do content_for(:foo) { "foo" } content_for(:foo) { "bar" } content_for(:bar) { "WON'T RENDER ME" } content_for(:foo) { "baz" } expect(yield_content(:foo)).to eq("foobarbaz") end it 'renders multiple blocks more than once' do content_for(:foo) { "foo" } content_for(:foo) { "bar" } content_for(:bar) { "WON'T RENDER ME" } content_for(:foo) { "baz" } 3.times { expect(yield_content(:foo)).to eq("foobarbaz") } end it 'passes values to the blocks' do content_for(:foo) { |a| a.upcase } expect(yield_content(:foo, 'a')).to eq("A") expect(yield_content(:foo, 'b')).to eq("B") end it 'clears named blocks with the specified key' do content_for(:foo) { "foo" } expect(yield_content(:foo)).to eq("foo") clear_content_for(:foo) expect(yield_content(:foo)).to be_empty end it 'takes an immediate value instead of a block' do content_for(:foo, "foo") expect(yield_content(:foo)).to eq("foo") end context 'when flush option was disabled' do it 'append content' do content_for(:foo, "foo") content_for(:foo, "bar") expect(yield_content(:foo)).to eq("foobar") end end context 'when flush option was enabled' do it 'flush first content' do content_for(:foo, "foo") content_for(:foo, "bar", flush: true) expect(yield_content(:foo)).to eq("bar") end end end # TODO: liquid markaby builder nokogiri engines = %w[erb erubi haml hamlit slim] engines.each do |inner| describe inner.capitalize do before :all do begin require inner rescue LoadError => e skip "Skipping: " << e.message end end describe "with yield_content in Ruby" do it 'renders blocks declared with the same key you use when rendering' do render inner, :same_key expect(yield_content(:foo).strip).to eq("foo") end it 'renders blocks more than once' do render inner, :same_key 3.times { expect(yield_content(:foo).strip).to eq("foo") } end it 'does not render a block with a different key' do render inner, :different_key expect(yield_content(:foo)).to be_empty end it 'renders default content if no block matches the key and a default block is specified' do render inner, :different_key expect(yield_content(:foo) { "foo" }).to eq("foo") end it 'renders multiple blocks with the same key' do render inner, :multiple_blocks expect(yield_content(:foo).gsub(/\s/, '')).to eq("foobarbaz") end it 'renders multiple blocks more than once' do render inner, :multiple_blocks 3.times { expect(yield_content(:foo).gsub(/\s/, '')).to eq("foobarbaz") } end it 'passes values to the blocks' do render inner, :takes_values expect(yield_content(:foo, 1, 2).gsub(/\s/, '')).to eq("<i>1</i>2") end end describe "with content_for in Ruby" do it 'renders blocks declared with the same key you use when rendering' do content_for(:foo) { "foo" } expect(render(inner, :layout)).to eq("foo") end it 'renders blocks more than once' do content_for(:foo) { "foo" } expect(render(inner, :multiple_yields)).to eq("foofoofoo") end it 'does not render a block with a different key' do content_for(:bar) { "foo" } expect(render(inner, :layout)).to be_empty end it 'renders multiple blocks with the same key' do content_for(:foo) { "foo" } content_for(:foo) { "bar" } content_for(:bar) { "WON'T RENDER ME" } content_for(:foo) { "baz" } expect(render(inner, :layout)).to eq("foobarbaz") end it 'renders multiple blocks more than once' do content_for(:foo) { "foo" } content_for(:foo) { "bar" } content_for(:bar) { "WON'T RENDER ME" } content_for(:foo) { "baz" } expect(render(inner, :multiple_yields)).to eq("foobarbazfoobarbazfoobarbaz") end it 'passes values to the blocks' do content_for(:foo) { |a,b| "<i>#{a}</i>#{b}" } expect(render(inner, :passes_values)).to eq("<i>1</i>2") end it 'clears named blocks with the specified key' do content_for(:foo) { "foo" } expect(render(inner, :layout)).to eq("foo") clear_content_for(:foo) expect(render(inner, :layout)).to be_empty end end describe "with content_for? in Ruby" do it 'renders block if key is set' do content_for(:foo) { "foot" } expect(render(inner, :footer)).to eq("foot") end it 'does not render a block if different key' do content_for(:different_key) { "foot" } expect(render(inner, :footer)).to be_empty end end engines.each do |outer| describe "with yield_content in #{outer.capitalize}" do def body last_response.body.gsub(/\s/, '') end before :all do begin require outer rescue LoadError => e skip "Skipping: " << e.message end end before do mock_app do helpers Sinatra::ContentFor set inner, :layout_engine => outer set :views, File.expand_path("content_for", __dir__) get('/:view') { render(inner, params[:view].to_sym) } get('/:layout/:view') do render inner, params[:view].to_sym, :layout => params[:layout].to_sym end end end describe 'with a default content block' do describe 'when content_for key exists' do it 'ignores default content and renders content' do expect(get('/yield_block/same_key')).to be_ok expect(body).to eq("foo") end end describe 'when content_for key is missing' do it 'renders default content block' do expect(get('/yield_block/different_key')).to be_ok expect(body).to eq("baz") end end end it 'renders content set as parameter' do expect(get('/parameter_value')).to be_ok expect(body).to eq("foo") end it 'renders blocks declared with the same key you use when rendering' do expect(get('/same_key')).to be_ok expect(body).to eq("foo") end it 'renders blocks more than once' do expect(get('/multiple_yields/same_key')).to be_ok expect(body).to eq("foofoofoo") end it 'does not render a block with a different key' do expect(get('/different_key')).to be_ok expect(body).to be_empty end it 'renders multiple blocks with the same key' do expect(get('/multiple_blocks')).to be_ok expect(body).to eq("foobarbaz") end it 'renders multiple blocks more than once' do expect(get('/multiple_yields/multiple_blocks')).to be_ok expect(body).to eq("foobarbazfoobarbazfoobarbaz") end it 'passes values to the blocks' do expect(get('/passes_values/takes_values')).to be_ok expect(body).to eq("<i>1</i>2") end end end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/config_file_spec.rb
sinatra-contrib/spec/config_file_spec.rb
require 'spec_helper' RSpec.describe Sinatra::ConfigFile do def config_file(*args, &block) mock_app do register Sinatra::ConfigFile set :root, File.expand_path('config_file', __dir__) instance_eval(&block) if block config_file(*args) end end it 'should set options from a simple config_file' do config_file 'key_value.yml' expect(settings.foo).to eq('bar') expect(settings.something).to eq(42) end it 'should create indifferent hashes' do config_file 'key_value.yml' expect(settings.nested['a']).to eq(1) expect(settings.nested[:a]).to eq(1) end it 'should render options in ERB tags when using .yml files' do config_file 'key_value.yml' expect(settings.bar).to eq "bar" expect(settings.something).to eq 42 expect(settings.nested['a']).to eq 1 expect(settings.nested[:a]).to eq 1 expect(settings.nested['b']).to eq 2 expect(settings.nested[:b]).to eq 2 end it 'should render options in ERB tags when using .yml.erb files' do config_file 'key_value.yml.erb' expect(settings.foo).to eq("bar") expect(settings.something).to eq(42) expect(settings.nested['a']).to eq(1) expect(settings.nested[:a]).to eq(1) expect(settings.nested['b']).to eq(2) expect(settings.nested[:b]).to eq(2) end it 'should render options in ERB tags when using .yaml files' do config_file 'key_value.yaml' expect(settings.foo).to eq("bar") expect(settings.something).to eq(42) expect(settings.nested['a']).to eq(1) expect(settings.nested[:a]).to eq(1) expect(settings.nested['b']).to eq(2) expect(settings.nested[:b]).to eq(2) end it 'should raise error if config file extension is not .yml, .yaml or .erb' do expect{ config_file 'config.txt' }.to raise_error(Sinatra::ConfigFile::UnsupportedConfigType) end it 'should recognize env specific settings per file' do config_file 'with_envs.yml' expect(settings.foo).to eq('test') end it 'should recognize env specific settings per setting' do config_file 'with_nested_envs.yml' expect(settings.database[:adapter]).to eq('sqlite') end it 'should not set present values to nil if the current env is missing' do # first let's check the test is actually working properly config_file('missing_env.yml') { set :foo => 42, :environment => :production } expect(settings.foo).to eq(10) # now test it config_file('missing_env.yml') { set :foo => 42, :environment => :test } expect(settings.foo).to eq(42) end it 'should prioritize settings in latter files' do # first let's check the test is actually working properly config_file 'key_value.yml' expect(settings.foo).to eq('bar') # now test it config_file 'key_value_override.yml' expect(settings.foo).to eq('foo') end context 'when file contains superfluous environments' do before { config_file 'with_env_defaults.yml' } it 'loads settings for the current environment anyway' do expect { settings.foo }.not_to raise_error end end context 'when file contains defaults' do before { config_file 'with_env_defaults.yml' } it 'uses the overridden value' do expect(settings.foo).to eq('test') end it 'uses the default value' do expect(settings.bar).to eq('baz') end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/cookies_spec.rb
sinatra-contrib/spec/cookies_spec.rb
require 'spec_helper' RSpec.describe Sinatra::Cookies do def cookie_route(*cookies, headers: {}, &block) result = nil set_cookie(cookies) @cookie_app.get('/') do result = instance_eval(&block) "ok" end get '/', {}, headers || {} expect(last_response).to be_ok expect(body).to eq("ok") result end def cookies(*set_cookies) cookie_route(*set_cookies) { cookies } end before do app = nil mock_app do helpers Sinatra::Cookies app = self end @cookie_app = app clear_cookies end describe :cookie_route do it 'runs the block' do ran = false cookie_route { ran = true } expect(ran).to be true end it 'returns the block result' do expect(cookie_route { 42 }).to eq(42) end end describe :== do it 'is comparable to hashes' do expect(cookies).to eq({}) end it 'is comparable to anything that responds to to_hash' do other = Struct.new(:to_hash).new({}) expect(cookies).to eq(other) end end describe :[] do it 'allows access to request cookies' do expect(cookies("foo=bar")["foo"]).to eq("bar") end it 'takes symbols as keys' do expect(cookies("foo=bar")[:foo]).to eq("bar") end it 'returns nil for missing keys' do expect(cookies("foo=bar")['bar']).to be_nil end it 'allows access to response cookies' do expect(cookie_route do response.set_cookie 'foo', 'bar' cookies['foo'] end).to eq('bar') end it 'favors response cookies over request cookies' do expect(cookie_route('foo=bar') do response.set_cookie 'foo', 'baz' cookies['foo'] end).to eq('baz') end it 'takes the last value for response cookies' do expect(cookie_route do response.set_cookie 'foo', 'bar' response.set_cookie 'foo', 'baz' cookies['foo'] end).to eq('baz') end end describe :[]= do it 'sets cookies to httponly' do expect(cookie_route do cookies['foo'] = 'bar' response['Set-Cookie'].lines.detect { |l| l.start_with? 'foo=' } end).to include('httponly') end it 'sets domain to nil if localhost' do headers = {'HTTP_HOST' => 'localhost'} expect(cookie_route(headers: headers) do cookies['foo'] = 'bar' response['Set-Cookie'] end).not_to include("domain") end it 'sets the domain' do expect(cookie_route do cookies['foo'] = 'bar' response['Set-Cookie'].lines.detect { |l| l.start_with? 'foo=' } end).to include('domain=example.org') end it 'sets path to / by default' do expect(cookie_route do cookies['foo'] = 'bar' response['Set-Cookie'].lines.detect { |l| l.start_with? 'foo=' } end).to include('path=/') end it 'sets path to the script_name if app is nested' do expect(cookie_route do request.script_name = '/foo' cookies['foo'] = 'bar' response['Set-Cookie'].lines.detect { |l| l.start_with? 'foo=' } end).to include('path=/foo') end it 'sets a cookie' do cookie_route { cookies['foo'] = 'bar' } expect(cookie_jar['foo']).to eq('bar') end it 'adds a value to the cookies hash' do expect(cookie_route do cookies['foo'] = 'bar' cookies['foo'] end).to eq('bar') end end describe :assoc do it 'behaves like Hash#assoc' do cookies('foo=bar').assoc('foo') == ['foo', 'bar'] end end if Hash.method_defined? :assoc describe :clear do it 'removes request cookies from cookies hash' do jar = cookies('foo=bar') expect(jar['foo']).to eq('bar') jar.clear expect(jar['foo']).to be_nil end it 'does not remove response cookies from cookies hash' do expect(cookie_route do cookies['foo'] = 'bar' cookies.clear cookies['foo'] end).to eq('bar') end it 'expires existing cookies' do expect(cookie_route("foo=bar") do cookies.clear response['Set-Cookie'] end).to include("foo=;", "expires=", "1970 00:00:00") end end describe :compare_by_identity? do it { expect(cookies).not_to be_compare_by_identity } end describe :default do it { expect(cookies.default).to be_nil } end describe :default_proc do it { expect(cookies.default_proc).to be_nil } end describe :delete do it 'removes request cookies from cookies hash' do jar = cookies('foo=bar') expect(jar['foo']).to eq('bar') jar.delete 'foo' expect(jar['foo']).to be_nil end it 'does not remove response cookies from cookies hash' do expect(cookie_route do cookies['foo'] = 'bar' cookies.delete 'foo' cookies['foo'] end).to eq('bar') end it 'expires existing cookies' do expect(cookie_route("foo=bar") do cookies.delete 'foo' response['Set-Cookie'] end).to include("foo=;", "expires=", "1970 00:00:00") end it 'honours the app cookie_options' do @cookie_app.class_eval do set :cookie_options, { :path => '/foo', :domain => 'bar.com', :secure => true, :httponly => true } end cookie_header = cookie_route("foo=bar") do cookies.delete 'foo' response['Set-Cookie'] end expect(cookie_header).to include("path=/foo;", "domain=bar.com;", "secure;", "httponly") end it 'does not touch other cookies' do expect(cookie_route("foo=bar", "bar=baz") do cookies.delete 'foo' cookies['bar'] end).to eq('baz') end it 'returns the previous value for request cookies' do expect(cookie_route("foo=bar") do cookies.delete "foo" end).to eq("bar") end it 'returns the previous value for response cookies' do expect(cookie_route do cookies['foo'] = 'bar' cookies.delete "foo" end).to eq("bar") end it 'returns nil for non-existing cookies' do expect(cookie_route { cookies.delete("foo") }).to be_nil end end describe :delete_if do it 'expires cookies that match the block' do expect(cookie_route('foo=bar') do cookies['bar'] = 'baz' cookies['baz'] = 'foo' cookies.delete_if { |*a| a.include? 'bar' } response['Set-Cookie'] end).to eq(["bar=baz; domain=example.org; path=/; httponly", "baz=foo; domain=example.org; path=/; httponly", "foo=; domain=example.org; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; httponly", "bar=; domain=example.org; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; httponly"]) end end describe :each do it 'loops through cookies' do keys = [] foo = nil bar = nil cookie_route('foo=bar', 'bar=baz') do cookies.each do |key, value| foo = value if key == 'foo' bar = value if key == 'bar' keys << key end end expect(keys.sort).to eq(['bar', 'foo']) expect(foo).to eq('bar') expect(bar).to eq('baz') end it 'favors response over request cookies' do seen = false key = nil value = nil cookie_route('foo=bar') do cookies[:foo] = 'baz' cookies.each do |k,v| key = k value = v end end expect(key).to eq('foo') expect(value).to eq('baz') expect(seen).to eq(false) end it 'does not loop through deleted cookies' do cookie_route('foo=bar') do cookies.delete :foo cookies.each { fail } end end it 'returns an enumerator' do keys = [] cookie_route('foo=bar') do enum = cookies.each enum.each { |key, value| keys << key } end keys.each{ |key| expect(key).to eq('foo')} end end describe :each_key do it 'loops through cookies' do keys = [] cookie_route('foo=bar', 'bar=baz') do cookies.each_key do |key| keys << key end end expect(keys.sort).to eq(['bar', 'foo']) end it 'only yields keys once' do seen = false cookie_route('foo=bar') do cookies[:foo] = 'baz' end expect(seen).to eq(false) end it 'does not loop through deleted cookies' do cookie_route('foo=bar') do cookies.delete :foo cookies.each_key { fail } end end it 'returns an enumerator' do keys = [] cookie_route('foo=bar') do enum = cookies.each_key enum.each { |key| keys << key } end keys.each{ |key| expect(key).to eq('foo')} end end describe :each_pair do it 'loops through cookies' do keys = [] foo = nil bar = nil cookie_route('foo=bar', 'bar=baz') do cookies.each_pair do |key, value| foo = value if key == 'foo' bar = value if key == 'bar' keys << key end end expect(keys.sort).to eq(['bar', 'foo']) expect(foo).to eq('bar') expect(bar).to eq('baz') end it 'favors response over request cookies' do seen = false key = nil value = nil cookie_route('foo=bar') do cookies[:foo] = 'baz' cookies.each_pair do |k, v| key = k value = v end end expect(key).to eq('foo') expect(value).to eq('baz') expect(seen).to eq(false) end it 'does not loop through deleted cookies' do cookie_route('foo=bar') do cookies.delete :foo cookies.each_pair { fail } end end it 'returns an enumerator' do keys = [] cookie_route('foo=bar') do enum = cookies.each_pair enum.each { |key, value| keys << key } end keys.each{ |key| expect(key).to eq('foo')} end end describe :each_value do it 'loops through cookies' do values = [] cookie_route('foo=bar', 'bar=baz') do cookies.each_value do |value| values << value end end expect(values.sort).to eq(['bar', 'baz']) end it 'favors response over request cookies' do value = nil cookie_route('foo=bar') do cookies[:foo] = 'baz' cookies.each_value do |v| value = v end end expect(value).to eq('baz') end it 'does not loop through deleted cookies' do cookie_route('foo=bar') do cookies.delete :foo cookies.each_value { fail } end end it 'returns an enumerator' do enum = nil cookie_route('foo=bar') do enum = cookies.each_value end enum.each { |value| expect(value).to eq('bar') } end end describe :empty? do it 'returns true if there are no cookies' do expect(cookies).to be_empty end it 'returns false if there are request cookies' do expect(cookies('foo=bar')).not_to be_empty end it 'returns false if there are response cookies' do expect(cookie_route do cookies['foo'] = 'bar' cookies.empty? end).to be false end it 'does not become true if response cookies are removed' do expect(cookie_route do cookies['foo'] = 'bar' cookies.delete :foo cookies.empty? end).to be false end it 'becomes true if request cookies are removed' do expect(cookie_route('foo=bar') do cookies.delete :foo cookies.empty? end).to be_truthy end it 'does not become true after clear' do expect(cookie_route('foo=bar', 'bar=baz') do cookies['foo'] = 'bar' cookies.clear cookies.empty? end).to be false end end describe :fetch do it 'returns values from request cookies' do expect(cookies('foo=bar').fetch('foo')).to eq('bar') end it 'returns values from response cookies' do expect(cookie_route do cookies['foo'] = 'bar' cookies.fetch('foo') end).to eq('bar') end it 'favors response over request cookies' do expect(cookie_route('foo=baz') do cookies['foo'] = 'bar' cookies.fetch('foo') end).to eq('bar') end it 'raises an exception if key does not exist' do error = if defined? JRUBY_VERSION IndexError else KeyError end expect { cookies.fetch('foo') }.to raise_exception(error) end it 'returns the block result if missing' do expect(cookies.fetch('foo') { 'bar' }).to eq('bar') end end describe :flatten do it { expect(cookies('foo=bar').flatten).to eq({'foo' => 'bar'}.flatten) } end if Hash.method_defined? :flatten describe :has_key? do it 'checks request cookies' do expect(cookies('foo=bar')).to have_key('foo') end it 'checks response cookies' do jar = cookies jar['foo'] = 'bar' expect(jar).to have_key(:foo) end it 'does not use deleted cookies' do jar = cookies('foo=bar') jar.delete :foo expect(jar).not_to have_key('foo') end end describe :has_value? do it 'checks request cookies' do expect(cookies('foo=bar')).to have_value('bar') end it 'checks response cookies' do jar = cookies jar[:foo] = 'bar' expect(jar).to have_value('bar') end it 'does not use deleted cookies' do jar = cookies('foo=bar') jar.delete :foo expect(jar).not_to have_value('bar') end end describe :include? do it 'checks request cookies' do expect(cookies('foo=bar')).to include('foo') end it 'checks response cookies' do jar = cookies jar['foo'] = 'bar' expect(jar).to include(:foo) end it 'does not use deleted cookies' do jar = cookies('foo=bar') jar.delete :foo expect(jar).not_to include('foo') end end describe :keep_if do it 'removes entries' do jar = cookies('foo=bar', 'bar=baz') jar.keep_if { |*args| args == ['bar', 'baz'] } expect(jar).to eq({'bar' => 'baz'}) end end describe :key do it 'checks request cookies' do expect(cookies('foo=bar').key('bar')).to eq('foo') end it 'checks response cookies' do jar = cookies jar['foo'] = 'bar' expect(jar.key('bar')).to eq('foo') end it 'returns nil when missing' do expect(cookies('foo=bar').key('baz')).to be_nil end end describe :key? do it 'checks request cookies' do expect(cookies('foo=bar').key?('foo')).to be true end it 'checks response cookies' do jar = cookies jar['foo'] = 'bar' expect(jar.key?(:foo)).to be true end it 'does not use deleted cookies' do jar = cookies('foo=bar') jar.delete :foo expect(jar.key?('foo')).to be false end end describe :keys do it { expect(cookies('foo=bar').keys).to eq(['foo']) } end describe :length do it { expect(cookies.length).to eq(0) } it { expect(cookies('foo=bar').length).to eq(1) } end describe :member? do it 'checks request cookies' do expect(cookies('foo=bar').member?('foo')).to be true end it 'checks response cookies' do jar = cookies jar['foo'] = 'bar' expect(jar.member?(:foo)).to be true end it 'does not use deleted cookies' do jar = cookies('foo=bar') jar.delete :foo expect(jar.member?('foo')).to be false end end describe :merge do it 'is mergeable with a hash' do expect(cookies('foo=bar').merge(:bar => :baz)).to eq({"foo" => "bar", :bar => :baz}) end it 'does not create cookies' do jar = cookies('foo=bar') jar.merge(:bar => 'baz') expect(jar).not_to include(:bar) end it 'takes a block for conflict resolution' do update = {'foo' => 'baz', 'bar' => 'baz'} merged = cookies('foo=bar').merge(update) do |key, old, other| expect(key).to eq('foo') expect(old).to eq('bar') expect(other).to eq('baz') 'foo' end expect(merged['foo']).to eq('foo') end end describe :merge! do it 'creates cookies' do jar = cookies('foo=bar') jar.merge! :bar => 'baz' expect(jar).to include('bar') end it 'overrides existing values' do jar = cookies('foo=bar') jar.merge! :foo => "baz" expect(jar["foo"]).to eq("baz") end it 'takes a block for conflict resolution' do update = {'foo' => 'baz', 'bar' => 'baz'} jar = cookies('foo=bar') jar.merge!(update) do |key, old, other| expect(key).to eq('foo') expect(old).to eq('bar') expect(other).to eq('baz') 'foo' end expect(jar['foo']).to eq('foo') end end describe :rassoc do it 'behaves like Hash#assoc' do cookies('foo=bar').rassoc('bar') == ['foo', 'bar'] end end if Hash.method_defined? :rassoc describe :reject do it 'removes entries from new hash' do jar = cookies('foo=bar', 'bar=baz') sub = jar.reject { |*args| args == ['bar', 'baz'] } expect(sub).to eq({'foo' => 'bar'}) expect(jar['bar']).to eq('baz') end end describe :reject! do it 'removes entries' do jar = cookies('foo=bar', 'bar=baz') jar.reject! { |*args| args == ['bar', 'baz'] } expect(jar).to eq({'foo' => 'bar'}) end end describe :replace do it 'replaces entries' do jar = cookies('foo=bar', 'bar=baz') jar.replace 'foo' => 'baz', 'baz' => 'bar' expect(jar).to eq({'foo' => 'baz', 'baz' => 'bar'}) end end describe :set do it 'sets a cookie' do cookie_route { cookies.set('foo', value: 'bar') } expect(cookie_jar['foo']).to eq('bar') end it 'sets a cookie with httponly' do expect(cookie_route do request.script_name = '/foo' cookies.set('foo', value: 'bar', httponly: true) response['Set-Cookie'].lines.detect { |l| l.start_with? 'foo=' } end).to include('httponly') end it 'sets a cookie without httponly' do expect(cookie_route do request.script_name = '/foo' cookies.set('foo', value: 'bar', httponly: false) response['Set-Cookie'].lines.detect { |l| l.start_with? 'foo=' } end).not_to include('httponly') end end describe :select do it 'removes entries from new hash' do jar = cookies('foo=bar', 'bar=baz') sub = jar.select { |*args| args != ['bar', 'baz'] } expect(sub).to eq({'foo' => 'bar'}.select { true }) expect(jar['bar']).to eq('baz') end end describe :select! do it 'removes entries' do jar = cookies('foo=bar', 'bar=baz') jar.select! { |*args| args != ['bar', 'baz'] } expect(jar).to eq({'foo' => 'bar'}) end end if Hash.method_defined? :select! describe :shift do it 'removes from the hash' do jar = cookies('foo=bar') expect(jar.shift).to eq(['foo', 'bar']) expect(jar).not_to include('bar') end end describe :size do it { expect(cookies.size).to eq(0) } it { expect(cookies('foo=bar').size).to eq(1) } end describe :update do it 'creates cookies' do jar = cookies('foo=bar') jar.update :bar => 'baz' expect(jar).to include('bar') end it 'overrides existing values' do jar = cookies('foo=bar') jar.update :foo => "baz" expect(jar["foo"]).to eq("baz") end it 'takes a block for conflict resolution' do merge = {'foo' => 'baz', 'bar' => 'baz'} jar = cookies('foo=bar') jar.update(merge) do |key, old, other| expect(key).to eq('foo') expect(old).to eq('bar') expect(other).to eq('baz') 'foo' end expect(jar['foo']).to eq('foo') end end describe :value? do it 'checks request cookies' do expect(cookies('foo=bar').value?('bar')).to be true end it 'checks response cookies' do jar = cookies jar[:foo] = 'bar' expect(jar.value?('bar')).to be true end it 'does not use deleted cookies' do jar = cookies('foo=bar') jar.delete :foo expect(jar.value?('bar')).to be false end end describe :values do it { expect(cookies('foo=bar', 'bar=baz').values.sort).to eq(['bar', 'baz']) } end describe :values_at do it { expect(cookies('foo=bar', 'bar=baz').values_at('foo')).to eq(['bar']) } end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/multi_route_spec.rb
sinatra-contrib/spec/multi_route_spec.rb
require 'spec_helper' RSpec.describe Sinatra::MultiRoute do it 'does not break normal routing' do mock_app do register Sinatra::MultiRoute get('/') { 'normal' } end expect(get('/')).to be_ok expect(body).to eq('normal') end it 'supports multiple routes' do mock_app do register Sinatra::MultiRoute get('/foo', '/bar') { 'paths' } end expect(get('/foo')).to be_ok expect(body).to eq('paths') expect(get('/bar')).to be_ok expect(body).to eq('paths') end it 'triggers conditions' do count = 0 mock_app do register Sinatra::MultiRoute set(:some_condition) { |_| count += 1 } get('/foo', '/bar', :some_condition => true) { 'paths' } end expect(count).to eq(4) end it 'supports multiple verbs' do mock_app do register Sinatra::MultiRoute route('PUT', 'POST', '/') { 'verb' } end expect(post('/')).to be_ok expect(body).to eq('verb') expect(put('/')).to be_ok expect(body).to eq('verb') end it 'takes symbols as verbs' do mock_app do register Sinatra::MultiRoute route(:get, '/baz') { 'symbol as verb' } end expect(get('/baz')).to be_ok expect(body).to eq('symbol as verb') end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/haml_helpers_spec.rb
sinatra-contrib/spec/haml_helpers_spec.rb
require 'haml' require 'spec_helper' require 'sinatra/haml_helpers' RSpec.describe Sinatra::HamlHelpers do let(:quote_char) { Haml::VERSION >= "7.0.0" ? "\"" : "'" } describe "#surround" do it "renders correctly" do mock_app do helpers Sinatra::HamlHelpers get "/" do haml_code = <<~HAML %p != surround "(", ")" do %a{ href: "https://example.org/" } surrounded HAML haml haml_code end end get "/" html_code = <<~HTML <p> (<a href=#{quote_char}https://example.org/#{quote_char}>surrounded</a>) </p> HTML expect(body).to eq(html_code) end end describe "#precede" do it "renders correctly" do mock_app do helpers Sinatra::HamlHelpers get "/" do haml_code = <<~HAML %p != precede "* " do %a{ href: "https://example.org/" } preceded HAML haml haml_code end end get "/" html_code = <<~HTML <p> * <a href=#{quote_char}https://example.org/#{quote_char}>preceded</a> </p> HTML expect(body).to eq(html_code) end end describe "#succeed" do it "renders correctly" do mock_app do helpers Sinatra::HamlHelpers get "/" do haml_code = <<~HAML %p != succeed "." do %a{ href: "https://example.org/" } succeeded HAML haml haml_code end end get "/" html_code = <<~HTML <p> <a href=#{quote_char}https://example.org/#{quote_char}>succeeded</a>. </p> HTML expect(body).to eq(html_code) end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/extension_spec.rb
sinatra-contrib/spec/extension_spec.rb
require 'spec_helper' RSpec.describe Sinatra::Extension do module ExampleExtension extend Sinatra::Extension set :foo, :bar settings.set :bar, :blah configure :test, :production do set :reload_stuff, false end configure :development do set :reload_stuff, true end get '/' do "from extension, yay" end end before { mock_app { register ExampleExtension }} it('allows using set') { expect(settings.foo).to eq(:bar) } it('implements configure') { expect(settings.reload_stuff).to be false } it 'allows defing routes' do expect(get('/')).to be_ok expect(body).to eq("from extension, yay") end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/reloader_spec.rb
sinatra-contrib/spec/reloader_spec.rb
require 'spec_helper' require 'fileutils' RSpec.describe Sinatra::Reloader do # Returns the temporary directory. def tmp_dir File.expand_path('../tmp', __dir__) end # Returns the path of the Sinatra application file created by # +setup_example_app+. def app_file_path File.join(tmp_dir, "example_app_#{$example_app_counter}.rb") end # Returns the name of the Sinatra application created by # +setup_example_app+: 'ExampleApp1' for the first application, # 'ExampleApp2' fo the second one, and so on... def app_name "ExampleApp#{$example_app_counter}" end # Returns the (constant of the) Sinatra application created by # +setup_example_app+. def app_const Module.const_get(app_name) end # Writes a file with a Sinatra application using the template # located at <tt>specs/reloader/app.rb.erb</tt>. It expects an # +options+ hash, with an array of strings containing the # application's routes (+:routes+ key), a hash with the inline # template's names as keys and the bodys as values # (+:inline_templates+ key) and an optional application name # (+:name+) otherwise +app_name+ is used. # # It ensures to change the written file's mtime when it already # exists. def write_app_file(options={}) options[:routes] ||= ['get("/foo") { erb :foo }'] options[:inline_templates] ||= nil options[:extensions] ||= [] options[:middlewares] ||= [] options[:filters] ||= [] options[:errors] ||= {} options[:name] ||= app_name options[:enable_reloader] = true unless options[:enable_reloader] === false options[:parent] ||= 'Sinatra::Base' update_file(app_file_path) do |f| template_path = File.expand_path('reloader/app.rb.erb', __dir__) template = Tilt.new(template_path, nil, :trim => '<>') f.write template.render(Object.new, options) end end alias update_app_file write_app_file # It calls <tt>File.open(path, 'w', &block)</tt> all the times # needed to change the file's mtime. def update_file(path, &block) original_mtime = File.exist?(path) ? File.mtime(path) : Time.at(0) new_time = original_mtime + 1 File.open(path, 'w', &block) File.utime(new_time, new_time, path) end # Writes a Sinatra application to a file, requires the file, sets # the new application as the one being tested and enables the # reloader. def setup_example_app(options={}) $example_app_counter ||= 0 $example_app_counter += 1 FileUtils.mkdir_p(tmp_dir) write_app_file(options) $LOADED_FEATURES.delete app_file_path require app_file_path self.app = app_const app_const.enable :reloader end after(:all) { FileUtils.rm_rf(tmp_dir) } describe "default route reloading mechanism" do before(:each) do setup_example_app(:routes => ['get("/foo") { "foo" }']) end it "doesn't mess up the application" do expect(get('/foo').body).to eq('foo') end it "knows when a route has been modified" do update_app_file(:routes => ['get("/foo") { "bar" }']) expect(get('/foo').body).to eq('bar') end it "knows when a route has been added" do update_app_file( :routes => ['get("/foo") { "foo" }', 'get("/bar") { "bar" }'] ) expect(get('/foo').body).to eq('foo') expect(get('/bar').body).to eq('bar') end it "knows when a route has been removed" do update_app_file(:routes => ['get("/bar") { "bar" }']) expect(get('/foo').status).to eq(404) end it "doesn't try to reload a removed file" do update_app_file(:routes => ['get("/foo") { "i shall not be reloaded" }']) FileUtils.rm app_file_path expect(get('/foo').body.strip).to eq('foo') end end describe "default inline templates reloading mechanism" do before(:each) do setup_example_app( :routes => ['get("/foo") { erb :foo }'], :inline_templates => { :foo => 'foo' } ) end it "doesn't mess up the application" do expect(get('/foo').body.strip).to eq('foo') end it "reloads inline templates in the app file" do update_app_file( :routes => ['get("/foo") { erb :foo }'], :inline_templates => { :foo => 'bar' } ) expect(get('/foo').body.strip).to eq('bar') end it "reloads inline templates in other file" do setup_example_app(:routes => ['get("/foo") { erb :foo }']) template_file_path = File.join(tmp_dir, 'templates.rb') File.open(template_file_path, 'w') do |f| f.write "__END__\n\n@@foo\nfoo" end require template_file_path app_const.inline_templates= template_file_path expect(get('/foo').body.strip).to eq('foo') update_file(template_file_path) do |f| f.write "__END__\n\n@@foo\nbar" end expect(get('/foo').body.strip).to eq('bar') end end describe "default middleware reloading mechanism" do it "knows when a middleware has been added" do setup_example_app(:routes => ['get("/foo") { "foo" }']) update_app_file( :routes => ['get("/foo") { "foo" }'], :middlewares => [Rack::Head] ) get('/foo') # ...to perform the reload expect(app_const.middleware).not_to be_empty end it "knows when a middleware has been removed" do setup_example_app( :routes => ['get("/foo") { "foo" }'], :middlewares => [Rack::Head] ) update_app_file(:routes => ['get("/foo") { "foo" }']) get('/foo') # ...to perform the reload expect(app_const.middleware).to be_empty end end describe "default filter reloading mechanism" do it "knows when a before filter has been added" do setup_example_app(:routes => ['get("/foo") { "foo" }']) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :filters => ['before { @hi = "hi" }'] ) get('/foo') # ...to perform the reload }.to change { app_const.filters[:before].size }.by(1) end it "knows when an after filter has been added" do setup_example_app(:routes => ['get("/foo") { "foo" }']) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :filters => ['after { @bye = "bye" }'] ) get('/foo') # ...to perform the reload }.to change { app_const.filters[:after].size }.by(1) end it "knows when a before filter has been removed" do setup_example_app( :routes => ['get("/foo") { "foo" }'], :filters => ['before { @hi = "hi" }'] ) expect { update_app_file(:routes => ['get("/foo") { "foo" }']) get('/foo') # ...to perform the reload }.to change { app_const.filters[:before].size }.by(-1) end it "knows when an after filter has been removed" do setup_example_app( :routes => ['get("/foo") { "foo" }'], :filters => ['after { @bye = "bye" }'] ) expect { update_app_file(:routes => ['get("/foo") { "foo" }']) get('/foo') # ...to perform the reload }.to change { app_const.filters[:after].size }.by(-1) end end describe "error reloading" do before do setup_example_app( :routes => ['get("/secret") { 403 }'], :errors => { 403 => "'Access forbiden'" } ) end it "doesn't mess up the application" do expect(get('/secret')).to be_client_error expect(get('/secret').body.strip).to eq('Access forbiden') end it "knows when a error has been added" do update_app_file(:errors => { 404 => "'Nowhere'" }) expect(get('/nowhere')).to be_not_found expect(get('/nowhere').body).to eq('Nowhere') end it "knows when a error has been removed" do update_app_file(:routes => ['get("/secret") { 403 }']) expect(get('/secret')).to be_client_error expect(get('/secret').body).not_to eq('Access forbiden') end it "knows when a error has been modified" do update_app_file( :routes => ['get("/secret") { 403 }'], :errors => { 403 => "'What are you doing here?'" } ) expect(get('/secret')).to be_client_error expect(get('/secret').body).to eq('What are you doing here?') end end describe "extension reloading" do it "doesn't duplicate routes with every reload" do module ::RouteExtension def self.registered(klass) klass.get('/bar') { 'bar' } end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['RouteExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['RouteExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.routes['GET'].size } end it "doesn't duplicate middleware with every reload" do module ::MiddlewareExtension def self.registered(klass) klass.use Rack::Head end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['MiddlewareExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['MiddlewareExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.middleware.size } end it "doesn't duplicate before filters with every reload" do module ::BeforeFilterExtension def self.registered(klass) klass.before { @hi = 'hi' } end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['BeforeFilterExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['BeforeFilterExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.filters[:before].size } end it "doesn't duplicate after filters with every reload" do module ::AfterFilterExtension def self.registered(klass) klass.after { @bye = 'bye' } end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['AfterFilterExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['AfterFilterExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.filters[:after].size } end end describe ".dont_reload" do before(:each) do setup_example_app( :routes => ['get("/foo") { erb :foo }'], :inline_templates => { :foo => 'foo' } ) end it "allows to specify a file to stop from being reloaded" do app_const.dont_reload app_file_path update_app_file(:routes => ['get("/foo") { "bar" }']) expect(get('/foo').body.strip).to eq('foo') end it "allows to specify a glob to stop matching files from being reloaded" do app_const.dont_reload '**/*.rb' update_app_file(:routes => ['get("/foo") { "bar" }']) expect(get('/foo').body.strip).to eq('foo') end it "doesn't interfere with other application's reloading policy" do app_const.dont_reload '**/*.rb' setup_example_app(:routes => ['get("/foo") { "foo" }']) update_app_file(:routes => ['get("/foo") { "bar" }']) expect(get('/foo').body.strip).to eq('bar') end end describe ".also_reload" do before(:each) do setup_example_app(:routes => ['get("/foo") { Foo.foo }']) @foo_path = File.join(tmp_dir, 'foo.rb') update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "foo" end end' end $LOADED_FEATURES.delete @foo_path require @foo_path app_const.also_reload @foo_path end it "allows to specify a file to be reloaded" do expect(get('/foo').body.strip).to eq('foo') update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end expect(get('/foo').body.strip).to eq('bar') end it "allows to specify glob to reaload matching files" do expect(get('/foo').body.strip).to eq('foo') update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end expect(get('/foo').body.strip).to eq('bar') end it "doesn't try to reload a removed file" do update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end FileUtils.rm @foo_path expect(get('/foo').body.strip).to eq('foo') end it "doesn't interfere with other application's reloading policy" do app_const.also_reload '**/*.rb' setup_example_app(:routes => ['get("/foo") { Foo.foo }']) expect(get('/foo').body.strip).to eq('foo') update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end expect(get('/foo').body.strip).to eq('foo') end end describe ".after_reload" do before(:each) do $reloaded = nil setup_example_app(:routes => ['get("/foo") { Foo.foo }']) @foo_path = File.join(tmp_dir, 'foo.rb') update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "foo" end end' end $LOADED_FEATURES.delete @foo_path require @foo_path app_const.also_reload @foo_path end it "allows block execution after reloading files" do app_const.after_reload do |files| $reloaded = files end expect($reloaded).to eq(nil) expect(get('/foo').body.strip).to eq('foo') expect($reloaded).to eq(nil) # after_reload was not called update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end expect(get("/foo").body.strip).to eq("bar") # Makes the reload happen expect($reloaded.size).to eq(1) expect(File.basename($reloaded[0])).to eq(File.basename(@foo_path)) end it "does not break block without input param" do app_const.after_reload do $reloaded = "worked without param" end expect($reloaded).to eq(nil) expect(get('/foo').body.strip).to eq('foo') expect($reloaded).to eq(nil) # after_reload was not called update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end expect { get("/foo") }.to_not raise_error # Makes the reload happen expect($reloaded).to eq("worked without param") end it "handles lambdas with arity 0" do user_proc = -> { $reloaded = "lambda?=true arity=0" } expect { user_proc.call(1) }.to raise_error(ArgumentError) # What we avoid app_const.after_reload(&user_proc) expect($reloaded).to eq(nil) expect(get('/foo').body.strip).to eq('foo') expect($reloaded).to eq(nil) # after_reload was not called update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end expect { get("/foo") }.to_not raise_error # Makes the reload happen expect($reloaded).to eq("lambda?=true arity=0") end end it "automatically registers the reloader in the subclasses" do class ::Parent < Sinatra::Base register Sinatra::Reloader enable :reloader end setup_example_app( :routes => ['get("/foo") { "foo" }'], :enable_reloader => false, :parent => 'Parent' ) update_app_file( :routes => ['get("/foo") { "bar" }'], :enable_reloader => false, :parent => 'Parent' ) expect(get('/foo').body).to eq('bar') end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/respond_with_spec.rb
sinatra-contrib/spec/respond_with_spec.rb
require 'multi_json' require 'spec_helper' require 'okjson' RSpec.describe Sinatra::RespondWith do def respond_app(&block) mock_app do set :app_file, __FILE__ set :views, root + '/respond_with' register Sinatra::RespondWith class_eval(&block) end end def respond_to(*args, &block) respond_app { get('/') { respond_to(*args, &block) } } end def respond_with(*args, &block) respond_app { get('/') { respond_with(*args, &block) } } end def req(*types) path = types.shift if types.first.is_a?(String) && types.first.start_with?('/') accept = types.map { |t| Sinatra::Base.mime_type(t).to_s }.join ',' get (path || '/'), {}, 'HTTP_ACCEPT' => accept end describe "Helpers#respond_to" do it 'allows defining handlers by file extensions' do respond_to do |format| format.html { "html!" } format.json { "json!" } end expect(req(:html).body).to eq("html!") expect(req(:json).body).to eq("json!") end it 'respects quality' do respond_to do |format| format.html { "html!" } format.json { "json!" } end expect(req("text/html;q=0.7, application/json;q=0.3").body).to eq("html!") expect(req("text/html;q=0.3, application/json;q=0.7").body).to eq("json!") end it 'allows using mime types' do respond_to do |format| format.on('text/html') { "html!" } format.json { "json!" } end expect(req(:html).body).to eq("html!") end it 'allows using wildcards in format matchers' do respond_to do |format| format.on('text/*') { "text!" } format.json { "json!" } end expect(req(:html).body).to eq("text!") end it 'allows using catch all wildcards in format matchers' do respond_to do |format| format.on('*/*') { "anything!" } format.json { "json!" } end expect(req(:html).body).to eq("anything!") end it 'prefers concret over generic' do respond_to do |format| format.on('text/*') { "text!" } format.on('*/*') { "anything!" } format.json { "json!" } end expect(req(:json).body).to eq("json!") expect(req(:html).body).to eq("text!") end it 'does not set up default handlers' do respond_to expect(req).not_to be_ok expect(status).to eq(500) expect(body).to eq("Unknown template engine") end end describe "Helpers#respond_with" do describe "matching" do it 'allows defining handlers by file extensions' do respond_with(:ignore) do |format| format.html { "html!" } format.json { "json!" } end expect(req(:html).body).to eq("html!") expect(req(:json).body).to eq("json!") end it 'respects quality' do respond_with(:ignore) do |format| format.html { "html!" } format.json { "json!" } end expect(req("text/html;q=0.7, application/json;q=0.3").body).to eq("html!") expect(req("text/html;q=0.3, application/json;q=0.7").body).to eq("json!") end it 'allows using mime types' do respond_with(:ignore) do |format| format.on('text/html') { "html!" } format.json { "json!" } end expect(req(:html).body).to eq("html!") end it 'allows using wildcards in format matchers' do respond_with(:ignore) do |format| format.on('text/*') { "text!" } format.json { "json!" } end expect(req(:html).body).to eq("text!") end it 'allows using catch all wildcards in format matchers' do respond_with(:ignore) do |format| format.on('*/*') { "anything!" } format.json { "json!" } end expect(req(:html).body).to eq("anything!") end it 'prefers concret over generic' do respond_with(:ignore) do |format| format.on('text/*') { "text!" } format.on('*/*') { "anything!" } format.json { "json!" } end expect(req(:json).body).to eq("json!") expect(req(:html).body).to eq("text!") end end describe "default behavior" do it 'converts objects to json out of the box' do respond_with 'a' => 'b' expect(OkJson.decode(req(:json).body)).to eq({'a' => 'b'}) end it 'handles multiple routes correctly' do respond_app do get('/') { respond_with 'a' => 'b' } get('/:name') { respond_with 'a' => params[:name] } end expect(OkJson.decode(req('/', :json).body)).to eq({'a' => 'b'}) expect(OkJson.decode(req('/b', :json).body)).to eq({'a' => 'b'}) expect(OkJson.decode(req('/c', :json).body)).to eq({'a' => 'c'}) end it "calls to_EXT if available" do respond_with Struct.new(:to_pdf).new("hello") expect(req(:pdf).body).to eq("hello") end it 'results in a 500 if format cannot be produced' do respond_with({}) expect(req(:html)).not_to be_ok expect(status).to eq(500) expect(body).to eq("Unknown template engine") end end describe 'templates' do it 'looks for templates with name.target.engine' do respond_with :foo, :name => 'World' expect(req(:html)).to be_ok expect(body).to eq("Hello World!") end it 'looks for templates with name.engine for specific engines' do respond_with :bar expect(req(:html)).to be_ok expect(body).to eq("guten Tag!") end it 'does not use name.engine for engines producing other formats' do respond_with :not_html expect(req(:html)).not_to be_ok expect(status).to eq(500) expect(body).to eq("Unknown template engine") end it 'falls back to #json if no template is found' do respond_with :foo, :name => 'World' expect(req(:json)).to be_ok expect(OkJson.decode(body)).to eq({'name' => 'World'}) end it 'favors templates over #json' do respond_with :bar, :name => 'World' expect(req(:json)).to be_ok expect(body).to eq('json!') end it 'falls back to to_EXT if no template is found' do object = {:name => 'World'} def object.to_pdf; "hi" end respond_with :foo, object expect(req(:pdf)).to be_ok expect(body).to eq("hi") end unless defined? JRUBY_VERSION it 'uses yajl for json' do respond_with :baz expect(req(:json)).to be_ok expect(body).to eq("\"yajl!\"") end end end describe 'customizing' do it 'allows customizing' do respond_with(:foo, :name => 'World') { |f| f.html { 'html!' }} expect(req(:html)).to be_ok expect(body).to eq("html!") end it 'falls back to default behavior if none matches' do respond_with(:foo, :name => 'World') { |f| f.json { 'json!' }} expect(req(:html)).to be_ok expect(body).to eq("Hello World!") end it 'favors generic rule over default behavior' do respond_with(:foo, :name => 'World') { |f| f.on('*/*') { 'generic!' }} expect(req(:html)).to be_ok expect(body).to eq("generic!") end end describe "inherited" do it "registers RespondWith in an inherited app" do app = Sinatra.new do set :app_file, __FILE__ set :views, root + '/respond_with' register Sinatra::RespondWith get '/a' do respond_with :json end end self.app = Sinatra.new(app) expect(req('/a', :json)).not_to be_ok end end end describe :respond_to do it 'acts as global provides condition' do respond_app do respond_to :json, :html get('/a') { 'ok' } get('/b') { 'ok' } end expect(req('/b', :xml)).not_to be_ok expect(req('/b', :html)).to be_ok end it 'still allows provides' do respond_app do respond_to :json, :html get('/a') { 'ok' } get('/b', :provides => :json) { 'ok' } end expect(req('/b', :html)).not_to be_ok expect(req('/b', :json)).to be_ok end it 'plays well with namespaces' do respond_app do register Sinatra::Namespace namespace '/a' do respond_to :json get { 'json' } end get('/b') { 'anything' } end expect(req('/a', :html)).not_to be_ok expect(req('/b', :html)).to be_ok end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/quiet_logger_spec.rb
sinatra-contrib/spec/quiet_logger_spec.rb
require 'spec_helper' require 'sinatra/quiet_logger' require 'logger' RSpec.describe Sinatra::QuietLogger do it 'logs just paths not excluded' do log = StringIO.new logger = Logger.new(log) mock_app do use Rack::CommonLogger, logger set :quiet_logger_prefixes, %w(quiet asset) register Sinatra::QuietLogger get('/log') { 'in log' } get('/quiet') { 'not in log' } end get('/log') get('/quiet') str = log.string expect(str).to include('GET /log') expect(str).to_not include('GET /quiet') end it 'warns about not setting quiet_logger_prefixes' do expect { mock_app do register Sinatra::QuietLogger end }.to output("You need to specify the paths you wish to exclude from logging via `set :quiet_logger_prefixes, %w(images css fonts)`\n").to_stderr end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/capture_spec.rb
sinatra-contrib/spec/capture_spec.rb
# -*- coding: utf-8 -*- require 'slim' require 'spec_helper' RSpec.describe Sinatra::Capture do subject do Sinatra.new do enable :inline_templates helpers Sinatra::Capture end.new! end Tilt.prefer Tilt::ERBTemplate extend Forwardable def_delegators :subject, :capture, :capture_later def render(engine, template) subject.send(:render, engine, template.to_sym).strip.gsub(/\s+/, ' ') end shared_examples_for "a template language" do |engine| lang = engine if engine == :erubi lang = :erb end if engine == :hamlit lang = :haml end require "#{engine}" it "captures content" do expect(render(engine, "simple_#{lang}")).to eq("Say Hello World!") end it "allows nested captures" do expect(render(engine, "nested_#{lang}")).to eq("Say Hello World!") end end describe('haml') { it_behaves_like "a template language", :haml } describe('hamlit') { it_behaves_like "a template language", :hamlit } describe('slim') { it_behaves_like "a template language", :slim } describe('erubi') { it_behaves_like "a template language", :erubi } describe 'erb' do it_behaves_like "a template language", :erb it "handles utf-8 encoding" do expect(render(:erb, "utf_8")).to eq("UTF-8 –") end it "handles ISO-8859-1 encoding" do expect(render(:erb, "iso_8859_1")).to eq("ISO-8859-1 -") end end describe 'without templates' do it 'captures empty blocks' do expect(capture {}).to be_nil end end end __END__ @@ simple_erb Say <% a = capture do %>World<% end %> Hello <%= a %>! @@ nested_erb Say <% a = capture do %> <% b = capture do %>World<% end %> <%= b %>! <% end %> Hello <%= a.strip %> @@ simple_slim | Say - a = capture do | World | Hello #{a.strip}! @@ nested_slim | Say - a = capture do - b = capture do | World | #{b.strip}! | Hello #{a.strip} @@ simple_haml Say - a = capture do World Hello #{a.strip}! @@ nested_haml Say - a = capture do - b = capture do World #{b.strip}! Hello #{a.strip} @@ utf_8 <% a = capture do %>–<% end %> UTF-8 <%= a %> @@ iso_8859_1 <% a = capture do %>-<% end %> ISO-8859-1 <%= a.force_encoding("iso-8859-1") %>
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/namespace_spec.rb
sinatra-contrib/spec/namespace_spec.rb
require 'spec_helper' RSpec.describe Sinatra::Namespace do verbs = [:get, :head, :post, :put, :delete, :options, :patch] def mock_app(&block) super do register Sinatra::Namespace class_eval(&block) end end def namespace(*args, &block) mock_app { namespace(*args, &block) } end verbs.each do |verb| describe "HTTP #{verb.to_s.upcase}" do it 'prefixes the path with the namespace' do namespace('/foo') { send(verb, '/bar') { 'baz' }} expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('baz') unless verb == :head expect(send(verb, '/foo/baz')).not_to be_ok end describe 'redirect_to' do it 'redirect within namespace' do namespace('/foo') { send(verb, '/bar') { redirect_to '/foo_bar' }} expect(send(verb, '/foo/bar')).to be_redirect expect(send(verb, '/foo/bar').location).to include("/foo/foo_bar") end end context 'when namespace is a string' do it 'accepts routes with no path' do namespace('/foo') { send(verb) { 'bar' } } expect(send(verb, '/foo')).to be_ok expect(body).to eq('bar') unless verb == :head end it 'accepts the path as a named parameter' do namespace('/foo') { send(verb, '/:bar') { params[:bar] }} expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('bar') unless verb == :head expect(send(verb, '/foo/baz')).to be_ok expect(body).to eq('baz') unless verb == :head end it 'accepts the path as a regular expression' do namespace('/foo') { send(verb, /\/\d\d/) { 'bar' }} expect(send(verb, '/foo/12')).to be_ok expect(body).to eq 'bar' unless verb == :head expect(send(verb, '/foo/123')).not_to be_ok end end context 'when namespace is a named parameter' do it 'accepts routes with no path' do namespace('/:foo') { send(verb) { 'bar' } } expect(send(verb, '/foo')).to be_ok expect(body).to eq('bar') unless verb == :head end it 'sets the parameter correctly' do namespace('/:foo') { send(verb, '/bar') { params[:foo] }} expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('foo') unless verb == :head expect(send(verb, '/fox/bar')).to be_ok expect(body).to eq('fox') unless verb == :head expect(send(verb, '/foo/baz')).not_to be_ok end it 'accepts the path as a named parameter' do namespace('/:foo') { send(verb, '/:bar') { params[:bar] }} expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('bar') unless verb == :head expect(send(verb, '/foo/baz')).to be_ok expect(body).to eq('baz') unless verb == :head end it 'accepts the path as regular expression' do namespace('/:foo') { send(verb, %r{/bar}) { params[:foo] }} expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('foo') unless verb == :head expect(send(verb, '/fox/bar')).to be_ok expect(body).to eq('fox') unless verb == :head expect(send(verb, '/foo/baz')).not_to be_ok end end context 'when namespace is a regular expression' do it 'accepts routes with no path' do namespace(%r{/foo}) { send(verb) { 'bar' } } expect(send(verb, '/foo')).to be_ok expect(body).to eq('bar') unless verb == :head end it 'accepts the path as a named parameter' do namespace(%r{/foo}) { send(verb, '/:bar') { params[:bar] }} expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('bar') unless verb == :head expect(send(verb, '/foo/baz')).to be_ok expect(body).to eq('baz') unless verb == :head end it 'accepts the path as a regular expression' do namespace(/\/\d\d/) { send(verb, /\/\d\d/) { 'foo' }} expect(send(verb, '/23/12')).to be_ok expect(body).to eq('foo') unless verb == :head expect(send(verb, '/123/12')).not_to be_ok end describe "before/after filters" do it 'trigger before filter' do ran = false namespace(/\/foo\/([^\/&?]+)\/bar\/([^\/&?]+)\//) { before { ran = true };} send(verb, '/bar/') expect(ran).to eq(false) send(verb, '/foo/1/bar/1/') expect(ran).to eq(true) end it 'trigger after filter' do ran = false namespace(/\/foo\/([^\/&?]+)\/bar\/([^\/&?]+)\//) { after { ran = true };} send(verb, '/bar/') expect(ran).to eq(false) send(verb, '/foo/1/bar/1/') expect(ran).to eq(true) end end describe 'helpers' do it 'are defined using the helpers method' do namespace(/\/foo\/([^\/&?]+)\/bar\/([^\/&?]+)\//) do helpers do def foo 'foo' end end send verb, '' do foo.to_s end end expect(send(verb, '/foo/1/bar/1/')).to be_ok expect(body).to eq('foo') unless verb == :head end end end context 'when namespace is a splat' do it 'accepts the path as a splat' do namespace('/*') { send(verb, '/*') { params[:splat].join ' - ' }} expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('foo - bar') unless verb == :head end end describe 'before-filters' do specify 'are triggered' do ran = false namespace('/foo') { before { ran = true }} send(verb, '/foo') expect(ran).to be true end specify 'are not triggered for a different namespace' do ran = false namespace('/foo') { before { ran = true }} send(verb, '/fox') expect(ran).to be false end end describe 'after-filters' do specify 'are triggered' do ran = false namespace('/foo') { after { ran = true }} send(verb, '/foo') expect(ran).to be true end specify 'are not triggered for a different namespace' do ran = false namespace('/foo') { after { ran = true }} send(verb, '/fox') expect(ran).to be false end end describe 'conditions' do context 'when the namespace has no prefix' do specify 'are accepted in the namespace' do mock_app do namespace(:host_name => 'example.com') { send(verb) { 'yes' }} send(verb, '/') { 'no' } end send(verb, '/', {}, 'HTTP_HOST' => 'example.com') expect(last_response).to be_ok expect(body).to eq('yes') unless verb == :head send(verb, '/', {}, 'HTTP_HOST' => 'example.org') expect(last_response).to be_ok expect(body).to eq('no') unless verb == :head end specify 'are accepted in the route definition' do namespace :host_name => 'example.com' do send(verb, '/foo', :provides => :txt) { 'ok' } end expect(send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/plain')).to be_ok expect(send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/html')).not_to be_ok expect(send(verb, '/foo', {}, 'HTTP_HOST' => 'example.org', 'HTTP_ACCEPT' => 'text/plain')).not_to be_ok end specify 'are accepted in the before-filter' do ran = false namespace :provides => :txt do before('/foo', :host_name => 'example.com') { ran = true } send(verb, '/*') { 'ok' } end send(verb, '/foo', {}, 'HTTP_HOST' => 'example.org', 'HTTP_ACCEPT' => 'text/plain') expect(ran).to be false send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/html') expect(ran).to be false send(verb, '/bar', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/plain') expect(ran).to be false send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/plain') expect(ran).to be true end specify 'are accepted in the after-filter' do ran = false namespace :provides => :txt do after('/foo', :host_name => 'example.com') { ran = true } send(verb, '/*') { 'ok' } end send(verb, '/foo', {}, 'HTTP_HOST' => 'example.org', 'HTTP_ACCEPT' => 'text/plain') expect(ran).to be false send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/html') expect(ran).to be false send(verb, '/bar', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/plain') expect(ran).to be false send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/plain') expect(ran).to be true end end context 'when the namespace is a string' do specify 'are accepted in the namespace' do namespace '/foo', :host_name => 'example.com' do send(verb) { 'ok' } end expect(send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com')).to be_ok expect(send(verb, '/foo', {}, 'HTTP_HOST' => 'example.org')).not_to be_ok end specify 'are accepted in the before-filter' do namespace '/foo' do before { @yes = nil } before(:host_name => 'example.com') { @yes = 'yes' } send(verb) { @yes || 'no' } end send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com') expect(last_response).to be_ok expect(body).to eq('yes') unless verb == :head send(verb, '/foo', {}, 'HTTP_HOST' => 'example.org') expect(last_response).to be_ok expect(body).to eq('no') unless verb == :head end specify 'are accepted in the after-filter' do ran = false namespace '/foo' do before(:host_name => 'example.com') { ran = true } send(verb) { 'ok' } end send(verb, '/foo', {}, 'HTTP_HOST' => 'example.org') expect(ran).to be false send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com') expect(ran).to be true end specify 'are accepted in the route definition' do namespace '/foo' do send(verb, :host_name => 'example.com') { 'ok' } end expect(send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com')).to be_ok expect(send(verb, '/foo', {}, 'HTTP_HOST' => 'example.org')).not_to be_ok end context 'when the namespace has a condition' do specify 'are accepted in the before-filter' do ran = false namespace '/', :provides => :txt do before(:host_name => 'example.com') { ran = true } send(verb) { 'ok' } end send(verb, '/', {}, 'HTTP_HOST' => 'example.org', 'HTTP_ACCEPT' => 'text/plain') expect(ran).to be false send(verb, '/', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/html') expect(ran).to be false send(verb, '/', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/plain') expect(ran).to be true end specify 'are accepted in the filters' do ran = false namespace '/f', :provides => :txt do before('oo', :host_name => 'example.com') { ran = true } send(verb, '/*') { 'ok' } end send(verb, '/foo', {}, 'HTTP_HOST' => 'example.org', 'HTTP_ACCEPT' => 'text/plain') expect(ran).to be false send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/html') expect(ran).to be false send(verb, '/far', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/plain') expect(ran).to be false send(verb, '/foo', {}, 'HTTP_HOST' => 'example.com', 'HTTP_ACCEPT' => 'text/plain') expect(ran).to be true end end end end describe 'helpers' do it 'are defined using the helpers method' do namespace '/foo' do helpers do def magic 42 end end send verb, '/bar' do magic.to_s end end expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('42') unless verb == :head end it 'can be defined as normal methods' do namespace '/foo' do def magic 42 end send verb, '/bar' do magic.to_s end end expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('42') unless verb == :head end it 'can be defined using module mixins' do mixin = Module.new do def magic 42 end end namespace '/foo' do helpers mixin send verb, '/bar' do magic.to_s end end expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('42') unless verb == :head end specify 'are unavailable outside the namespace where they are defined' do mock_app do namespace '/foo' do def magic 42 end send verb, '/bar' do magic.to_s end end send verb, '/' do magic.to_s end end expect { send verb, '/' }.to raise_error(NameError) end specify 'are unavailable outside the namespace that they are mixed into' do mixin = Module.new do def magic 42 end end mock_app do namespace '/foo' do helpers mixin send verb, '/bar' do magic.to_s end end send verb, '/' do magic.to_s end end expect { send verb, '/' }.to raise_error(NameError) end specify 'are available to nested namespaces' do mock_app do helpers do def magic 42 end end namespace '/foo' do send verb, '/bar' do magic.to_s end end end expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('42') unless verb == :head end specify 'can call super from nested definitions' do mock_app do helpers do def magic 42 end end namespace '/foo' do def magic super - 19 end send verb, '/bar' do magic.to_s end end end expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('23') unless verb == :head end end describe 'nesting' do it 'routes to nested namespaces' do namespace '/foo' do namespace '/bar' do send(verb, '/baz') { 'OKAY!!11!'} end end expect(send(verb, '/foo/bar/baz')).to be_ok expect(body).to eq('OKAY!!11!') unless verb == :head end it 'works correctly if deep nesting' do namespace '/a' do namespace '/b' do namespace '/c' do send(verb, '') { 'hey' } end end end expect(send(verb, '/a/b/c')).to be_ok expect(body).to eq('hey') unless verb == :head end it 'exposes helpers to nested namespaces' do namespace '/foo' do helpers do def magic 42 end end namespace '/bar' do send verb, '/baz' do magic.to_s end end end expect(send(verb, '/foo/bar/baz')).to be_ok expect(body).to eq('42') unless verb == :head end specify 'does not provide access to nested helper methods' do namespace '/foo' do namespace '/bar' do def magic 42 end send verb, '/baz' do magic.to_s end end send verb do magic.to_s end end expect { send verb, '/foo' }.to raise_error(NameError) end it 'accepts a nested namespace as a named parameter' do namespace('/:a') { namespace('/:b') { send(verb) { params[:a] }}} expect(send(verb, '/foo/bar')).to be_ok expect(body).to eq('foo') unless verb == :head end end describe 'error handling' do it 'can be customized using the not_found block' do namespace('/de') do not_found { 'nicht gefunden' } end expect(send(verb, '/foo').status).to eq 404 expect(last_response.body).not_to eq 'nicht gefunden' unless verb == :head expect(get('/en/foo').status).to eq 404 expect(last_response.body).not_to eq 'nicht gefunden' unless verb == :head expect(get('/de/foo').status).to eq 404 expect(last_response.body).to eq 'nicht gefunden' unless verb == :head end it 'can be customized for specific error codes' do namespace('/de') do error(404) { 'nicht gefunden' } end expect(send(verb, '/foo').status).to eq 404 expect(last_response.body).not_to eq 'nicht gefunden' unless verb == :head expect(get('/en/foo').status).to eq 404 expect(last_response.body).not_to eq 'nicht gefunden' unless verb == :head expect(get('/de/foo').status).to eq 404 expect(last_response.body).to eq 'nicht gefunden' unless verb == :head end it 'falls back to the handler defined in the base app' do mock_app do error(404) { 'not found...' } namespace('/en') do end namespace('/de') do error(404) { 'nicht gefunden' } end end expect(send(verb, '/foo').status).to eq 404 expect(last_response.body).to eq 'not found...' unless verb == :head expect(get('/en/foo').status).to eq 404 expect(last_response.body).to eq 'not found...' unless verb == :head expect(get('/de/foo').status).to eq 404 expect(last_response.body).to eq 'nicht gefunden' unless verb == :head end it 'can be customized for specific Exception classes' do mock_app do class AError < StandardError; end class BError < AError; end error(AError) do body('auth failed') 401 end namespace('/en') do get '/foo' do raise BError end end namespace('/de') do error(AError) do body('methode nicht erlaubt') 406 end get '/foo' do raise BError end end end expect(get('/en/foo').status).to eq 401 expect(last_response.body).to eq 'auth failed' unless verb == :head expect(get('/de/foo').status).to eq 406 expect(last_response.body).to eq 'methode nicht erlaubt' unless verb == :head end it "allows custom error handlers when namespace is declared as /en/:id. Issue #119" do mock_app { class CError < StandardError; end error { raise "should not come here" } namespace('/en/:id') do error(CError) { 201 } get '/?' do raise CError end end } expect(get('/en/1').status).to eq(201) end end unless verb == :head describe 'templates' do specify 'default to the base app\'s template' do mock_app do template(:foo) { 'hi' } send(verb, '/') { erb :foo } namespace '/foo' do send(verb) { erb :foo } end end expect(send(verb, '/').body).to eq 'hi' expect(send(verb, '/foo').body).to eq 'hi' end specify 'can be nested' do mock_app do template(:foo) { 'hi' } send(verb, '/') { erb :foo } namespace '/foo' do template(:foo) { 'ho' } send(verb) { erb :foo } end end expect(send(verb, '/').body).to eq 'hi' expect(send(verb, '/foo').body).to eq 'ho' end specify 'can use a custom views directory' do mock_app do set :views, File.expand_path('namespace', __dir__) send(verb, '/') { erb :foo } namespace('/foo') do set :views, File.expand_path('namespace/nested', __dir__) send(verb) { erb :foo } end end expect(send(verb, '/').body).to eq "hi\n" expect(send(verb, '/foo').body).to eq "ho\n" end specify 'default to the base app\'s layout' do mock_app do layout { 'he said: <%= yield %>' } template(:foo) { 'hi' } send(verb, '/') { erb :foo } namespace '/foo' do template(:foo) { 'ho' } send(verb) { erb :foo } end end expect(send(verb, '/').body).to eq 'he said: hi' expect(send(verb, '/foo').body).to eq 'he said: ho' end specify 'can define nested layouts' do mock_app do layout { 'Hello <%= yield %>!' } template(:foo) { 'World' } send(verb, '/') { erb :foo } namespace '/foo' do layout { 'Hi <%= yield %>!' } send(verb) { erb :foo } end end expect(send(verb, '/').body).to eq 'Hello World!' expect(send(verb, '/foo').body).to eq 'Hi World!' end specify 'can render strings' do mock_app do namespace '/foo' do send(verb) { erb 'foo' } end end expect(send(verb, '/foo').body).to eq 'foo' end specify 'can render strings nested' do mock_app do namespace '/foo' do namespace '/bar' do send(verb) { erb 'bar' } end end end expect(send(verb, '/foo/bar').body).to eq 'bar' end end end describe 'extensions' do specify 'provide read access to settings' do value = nil mock_app do set :foo, 42 namespace '/foo' do value = foo end end expect(value).to eq 42 end specify 'can be registered within a namespace' do a = b = nil extension = Module.new { define_method(:views) { 'CUSTOM!!!' } } mock_app do namespace '/' do register extension a = views end b = views end expect(a).to eq 'CUSTOM!!!' expect(b).not_to eq 'CUSTOM!!!' end specify 'trigger the route_added hook' do route = nil extension = Module.new extension.singleton_class.class_eval do define_method(:route_added) { |*r| route = r } end mock_app do namespace '/f' do register extension get('oo') { } end get('/bar') { } end expect(route[1]).to eq(Mustermann.new '/foo') end specify 'prevent app-global settings from being changed' do expect { namespace('/') { set :foo, :bar }}.to raise_error(ArgumentError) end end end end describe 'settings' do it 'provides access to top-level settings' do mock_app do set :foo, 'ok' namespace '/foo' do get '/bar' do settings.foo end end end expect(get('/foo/bar').status).to eq(200) expect(last_response.body).to eq('ok') end it 'sets hashes correctly' do mock_app do namespace '/foo' do set erb: 'o', haml: 'k' get '/bar' do settings.erb + settings.haml end end end expect(get('/foo/bar').status).to eq(200) expect(last_response.body).to eq('ok') end it 'uses some repro' do mock_app do set :foo, 42 namespace '/foo' do get '/bar' do #settings.respond_to?(:foo).to_s settings.foo.to_s end end end expect(get('/foo/bar').status).to eq(200) expect(last_response.body).to eq('42') end it 'allows checking setting existence with respond_to?' do mock_app do set :foo, 42 namespace '/foo' do get '/bar' do settings.respond_to?(:foo).to_s end end end expect(get('/foo/bar').status).to eq(200) expect(last_response.body).to eq('true') end it 'avoids executing filters even if prefix matches with other namespace' do mock_app do helpers do def dump_args(*args) args.inspect end end namespace '/foo' do helpers do def dump_args(*args) super(:foo, *args) end end get('') { dump_args } end namespace '/foo-bar' do helpers do def dump_args(*args) super(:foo_bar, *args) end end get('') { dump_args } end end get '/foo-bar' expect(last_response.body).to eq('[:foo_bar]') end end it 'forbids unknown engine settings' do expect { mock_app do namespace '/foo' do set :unknownsetting end end }.to raise_error(ArgumentError, 'may not set unknownsetting') end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/json_spec.rb
sinatra-contrib/spec/json_spec.rb
require 'multi_json' require 'spec_helper' require 'okjson' RSpec.shared_examples_for "a json encoder" do |lib, const| before do begin require lib if lib @encoder = eval(const) rescue LoadError skip "unable to load #{lib}" end end it "allows setting :encoder to #{const}" do enc = @encoder mock_app { get('/') { json({'foo' => 'bar'}, :encoder => enc) }} results_in 'foo' => 'bar' end it "allows setting settings.json_encoder to #{const}" do enc = @encoder mock_app do set :json_encoder, enc get('/') { json 'foo' => 'bar' } end results_in 'foo' => 'bar' end end RSpec.describe Sinatra::JSON do def mock_app(&block) super do class_eval(&block) end end def results_in(obj) expect(OkJson.decode(get('/').body)).to eq(obj) end it "encodes objects to json out of the box" do mock_app { get('/') { json :foo => [1, 'bar', nil] } } results_in 'foo' => [1, 'bar', nil] end it "sets the content type to 'application/json'" do mock_app { get('/') { json({}) } } expect(get('/')["Content-Type"]).to include("application/json") end it "allows overriding content type with :content_type" do mock_app { get('/') { json({}, :content_type => "foo/bar") } } expect(get('/')["Content-Type"]).to eq("foo/bar") end it "accepts shorthands for :content_type" do mock_app { get('/') { json({}, :content_type => :js) } } # Changed to "text/javascript" in Rack >3.0 # https://github.com/sinatra/sinatra/pull/1857#issuecomment-1445062212 expect(get('/')["Content-Type"]) .to eq("application/javascript;charset=utf-8").or eq("text/javascript;charset=utf-8") end it 'calls generate on :encoder if available' do enc = Object.new def enc.generate(obj) obj.inspect end mock_app { get('/') { json(42, :encoder => enc) }} expect(get('/').body).to eq('42') end it 'calls encode on :encoder if available' do enc = Object.new def enc.encode(obj) obj.inspect end mock_app { get('/') { json(42, :encoder => enc) }} expect(get('/').body).to eq('42') end it 'sends :encoder as method call if it is a Symbol' do mock_app { get('/') { json(42, :encoder => :inspect) }} expect(get('/').body).to eq('42') end it 'calls generate on settings.json_encoder if available' do enc = Object.new def enc.generate(obj) obj.inspect end mock_app do set :json_encoder, enc get('/') { json 42 } end expect(get('/').body).to eq('42') end it 'calls encode on settings.json_encode if available' do enc = Object.new def enc.encode(obj) obj.inspect end mock_app do set :json_encoder, enc get('/') { json 42 } end expect(get('/').body).to eq('42') end it 'sends settings.json_encode as method call if it is a Symbol' do mock_app do set :json_encoder, :inspect get('/') { json 42 } end expect(get('/').body).to eq('42') end describe('Yajl') { it_should_behave_like "a json encoder", "yajl", "Yajl::Encoder" } unless defined? JRUBY_VERSION describe('JSON') { it_should_behave_like "a json encoder", "json", "::JSON" } describe('OkJson') { it_should_behave_like "a json encoder", nil, "OkJson" } describe('to_json') { it_should_behave_like "a json encoder", "json", ":to_json" } describe('without') { it_should_behave_like "a json encoder", nil, "Sinatra::JSON" } end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/link_header_spec.rb
sinatra-contrib/spec/link_header_spec.rb
require 'spec_helper' RSpec.describe Sinatra::LinkHeader do before do mock_app do helpers Sinatra::LinkHeader before('/') { link 'something', :rel => 'from-filter', :foo => :bar } get '/' do link :something, 'booyah' end get '/style' do stylesheet '/style.css' end get '/prefetch' do prefetch '/foo' end get '/link_headers' do response['Link'] = "<foo> ;bar=\"baz\"" stylesheet '/style.css' prefetch '/foo' link_headers end end end describe :link do it "sets link headers" do get '/' expect(headers['Link']).to include('<booyah>; rel="something"') end it "returns link html tags" do get '/' expect(body).to eq('<link href="booyah" rel="something" />') end it "takes an options hash" do get '/' elements = ["<something>", "foo=\"bar\"", "rel=\"from-filter\""] expect(headers['Link'].split(",").first.strip.split('; ').sort).to eq(elements) end end describe :stylesheet do it 'sets link headers' do get '/style' expect(headers['Link']).to match(%r{^</style\.css>;}) end it 'sets type to text/css' do get '/style' expect(headers['Link']).to include('type="text/css"') end it 'sets rel to stylesheet' do get '/style' expect(headers['Link']).to include('rel="stylesheet"') end it 'returns html tag' do get '/style' expect(body).to match(%r{^<link href="/style\.css"}) end end describe :prefetch do it 'sets link headers' do get '/prefetch' expect(headers['Link']).to match(%r{^</foo>;}) end it 'sets rel to prefetch' do get '/prefetch' expect(headers['Link']).to include('rel="prefetch"') end it 'returns html tag' do get '/prefetch' expect(body).to eq('<link href="/foo" rel="prefetch" />') end end describe :link_headers do it 'generates html for all link headers' do get '/link_headers' expect(body).to include('<link href="/foo" rel="prefetch" />') expect(body).to include('<link href="/style.css" ') end it "respects Link headers not generated on its own" do get '/link_headers' expect(body).to include('<link href="foo" bar="baz" />') end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/streaming_spec.rb
sinatra-contrib/spec/streaming_spec.rb
require 'spec_helper' RSpec.describe Sinatra::Streaming do def stream(&block) rack_middleware = @use out = nil mock_app do rack_middleware.each { |args| use(*args) } helpers Sinatra::Streaming get('/') { out = stream(&block) } end get('/') out end def use(*args) @use << args end before do @use = [] end context 'stream test helper' do it 'runs the given block' do ran = false stream { ran = true } expect(ran).to be true end it 'returns the stream object' do out = stream { } expect(out).to be_a(Sinatra::Helpers::Stream) end it 'fires a request against that stream' do stream { |out| out << "Hello World!" } expect(last_response).to be_ok expect(body).to eq("Hello World!") end it 'passes the stream object to the block' do passed = nil returned = stream { |out| passed = out } expect(passed).to eq(returned) end end context Sinatra::Streaming::Stream do it 'should extend the stream object' do out = stream { } expect(out).to be_a(Sinatra::Streaming::Stream) end it 'should not extend stream objects of other apps' do out = nil mock_app { get('/') { out = stream { }}} get('/') expect(out).to be_a(Sinatra::Helpers::Stream) expect(out).not_to be_a(Sinatra::Streaming::Stream) end end context 'app' do it 'is the app instance the stream was created from' do out = stream { } expect(out.app).to be_a(Sinatra::Base) end end context 'lineno' do it 'defaults to 0' do expect(stream { }.lineno).to eq(0) end it 'does not increase on write' do stream do |out| out << "many\nlines\n" expect(out.lineno).to eq(0) end end it 'is writable' do out = stream { } out.lineno = 10 expect(out.lineno).to eq(10) end end context 'pos' do it 'defaults to 0' do expect(stream { }.pos).to eq(0) end it 'increases when writing data' do stream do |out| expect(out.pos).to eq(0) out << 'hi' expect(out.pos).to eq(2) end end it 'is writable' do out = stream { } out.pos = 10 expect(out.pos).to eq(10) end it 'aliased to #tell' do out = stream { } expect(out.tell).to eq(0) out.pos = 10 expect(out.tell).to eq(10) end end context 'closed' do it 'returns false while streaming' do stream { |out| expect(out).not_to be_closed } end it 'returns true after streaming' do expect(stream {}).to be_closed end end context 'map!' do it 'applies transformations later' do stream do |out| out.map! { |s| s.upcase } out << 'ok' end expect(body).to eq("OK") end it 'is chainable' do stream do |out| out.map! { |s| s.upcase } out.map! { |s| s.reverse } out << 'ok' end expect(body).to eq("KO") end it 'works with middleware' do middleware = Class.new do def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) body.map! { |s| s.upcase } [status, headers, body] end end use middleware stream { |out| out << "ok" } expect(body).to eq("OK") end it 'modifies each value separately' do stream do |out| out.map! { |s| s.reverse } out << "ab" << "cd" end expect(body).to eq("badc") end end context 'map' do it 'works with middleware' do middleware = Class.new do def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) [status, headers, body.map(&:upcase)] end end use middleware stream { |out| out << "ok" } expect(body).to eq("OK") end it 'is chainable' do middleware = Class.new do def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) [status, headers, body.map(&:upcase).map(&:reverse)] end end use middleware stream { |out| out << "ok" } expect(body).to eq("KO") end it 'can be written as each.map' do middleware = Class.new do def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) [status, headers, body.each.map(&:upcase)] end end use middleware stream { |out| out << "ok" } expect(body).to eq("OK") end it 'does not modify the original body' do stream do |out| out.map { |s| s.reverse } out << 'ok' end expect(body).to eq('ok') end end context 'write' do it 'writes to the stream' do stream { |out| out.write 'hi' } expect(body).to eq('hi') end it 'returns the number of bytes' do stream do |out| expect(out.write('hi')).to eq(2) expect(out.write('hello')).to eq(5) end end it 'accepts non-string objects' do stream do |out| expect(out.write(12)).to eq(2) end end it 'should be aliased to syswrite' do stream { |out| expect(out.syswrite('hi')).to eq(2) } expect(body).to eq('hi') end it 'should be aliased to write_nonblock' do stream { |out| expect(out.write_nonblock('hi')).to eq(2) } expect(body).to eq('hi') end end context 'print' do it 'writes to the stream' do stream { |out| out.print('hi') } expect(body).to eq('hi') end it 'accepts multiple arguments' do stream { |out| out.print(1, 2, 3, 4) } expect(body).to eq('1234') end it 'returns nil' do stream { |out| expect(out.print('hi')).to be_nil } end end context 'printf' do it 'writes to the stream' do stream { |out| out.printf('hi') } expect(body).to eq('hi') end it 'interpolates the format string' do stream { |out| out.printf("%s: %d", "answer", 42) } expect(body).to eq('answer: 42') end it 'returns nil' do stream { |out| expect(out.printf('hi')).to be_nil } end end context 'putc' do it 'writes the first character of a string' do stream { |out| out.putc('hi') } expect(body).to eq('h') end it 'writes the character corresponding to an integer' do stream { |out| out.putc(42) } expect(body).to eq('*') end it 'returns nil' do stream { |out| expect(out.putc('hi')).to be_nil } end end context 'puts' do it 'writes to the stream' do stream { |out| out.puts('hi') } expect(body).to eq("hi\n") end it 'accepts multiple arguments' do stream { |out| out.puts(1, 2, 3, 4) } expect(body).to eq("1\n2\n3\n4\n") end it 'returns nil' do stream { |out| expect(out.puts('hi')).to be_nil } end end context 'close' do it 'sets #closed? to true' do stream do |out| out.close expect(out).to be_closed end end it 'sets #closed_write? to true' do stream do |out| expect(out).not_to be_closed_write out.close expect(out).to be_closed_write end end it 'fires callbacks' do stream do |out| fired = false out.callback { fired = true } out.close expect(fired).to be true end end it 'prevents from further writing' do stream do |out| out.close expect { out << 'hi' }.to raise_error(IOError, 'not opened for writing') end end end context 'close_read' do it 'raises the appropriate exception' do expect { stream { |out| out.close_read }}. to raise_error(IOError, "closing non-duplex IO for reading") end end context 'closed_read?' do it('returns true') { stream { |out| expect(out).to be_closed_read }} end context 'rewind' do it 'resets pos' do stream do |out| out << 'hi' out.rewind expect(out.pos).to eq(0) end end it 'resets lineno' do stream do |out| out.lineno = 10 out.rewind expect(out.lineno).to eq(0) end end end raises = %w[ bytes eof? eof getbyte getc gets read read_nonblock readbyte readchar readline readlines readpartial sysread ungetbyte ungetc ] enum = %w[chars each_line each_byte each_char lines] dummies = %w[flush fsync internal_encoding pid] raises.each do |method| context method do it 'raises the appropriate exception' do expect { stream { |out| out.public_send(method) }}. to raise_error(IOError, "not opened for reading") end end end enum.each do |method| context method do it 'creates an Enumerator' do stream { |out| expect(out.public_send(method)).to be_a(Enumerator) } end it 'calling each raises the appropriate exception' do expect { stream { |out| out.public_send(method).each { }}}. to raise_error(IOError, "not opened for reading") end end end dummies.each do |method| context method do it 'returns nil' do stream { |out| expect(out.public_send(method)).to be_nil } end end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/okjson.rb
sinatra-contrib/spec/okjson.rb
# Copyright 2011 Keith Rarick # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # See https://github.com/kr/okjson for updates. require 'stringio' # Some parts adapted from # http://golang.org/src/pkg/json/decode.go and # http://golang.org/src/pkg/utf8/utf8.go module OkJson extend self # Decodes a json document in string s and # returns the corresponding ruby value. # String s must be valid UTF-8. If you have # a string in some other encoding, convert # it first. # # String values in the resulting structure # will be UTF-8. def decode(s) ts = lex(s) v, ts = textparse(ts) if ts.length > 0 raise Error, 'trailing garbage' end v end # Parses a "json text" in the sense of RFC 4627. # Returns the parsed value and any trailing tokens. # Note: this is almost the same as valparse, # except that it does not accept atomic values. def textparse(ts) if ts.length < 0 raise Error, 'empty' end typ, _, val = ts[0] case typ when '{' then objparse(ts) when '[' then arrparse(ts) else raise Error, "unexpected #{val.inspect}" end end # Parses a "value" in the sense of RFC 4627. # Returns the parsed value and any trailing tokens. def valparse(ts) if ts.length < 0 raise Error, 'empty' end typ, _, val = ts[0] case typ when '{' then objparse(ts) when '[' then arrparse(ts) when :val,:str then [val, ts[1..-1]] else raise Error, "unexpected #{val.inspect}" end end # Parses an "object" in the sense of RFC 4627. # Returns the parsed value and any trailing tokens. def objparse(ts) ts = eat('{', ts) obj = {} if ts[0][0] == '}' return obj, ts[1..-1] end k, v, ts = pairparse(ts) obj[k] = v if ts[0][0] == '}' return obj, ts[1..-1] end loop do ts = eat(',', ts) k, v, ts = pairparse(ts) obj[k] = v if ts[0][0] == '}' return obj, ts[1..-1] end end end # Parses a "member" in the sense of RFC 4627. # Returns the parsed values and any trailing tokens. def pairparse(ts) (typ, _, k), ts = ts[0], ts[1..-1] if typ != :str raise Error, "unexpected #{k.inspect}" end ts = eat(':', ts) v, ts = valparse(ts) [k, v, ts] end # Parses an "array" in the sense of RFC 4627. # Returns the parsed value and any trailing tokens. def arrparse(ts) ts = eat('[', ts) arr = [] if ts[0][0] == ']' return arr, ts[1..-1] end v, ts = valparse(ts) arr << v if ts[0][0] == ']' return arr, ts[1..-1] end loop do ts = eat(',', ts) v, ts = valparse(ts) arr << v if ts[0][0] == ']' return arr, ts[1..-1] end end end def eat(typ, ts) if ts[0][0] != typ raise Error, "expected #{typ} (got #{ts[0].inspect})" end ts[1..-1] end # Sans s and returns a list of json tokens, # excluding white space (as defined in RFC 4627). def lex(s) ts = [] while s.length > 0 typ, lexeme, val = tok(s) if typ == nil raise Error, "invalid character at #{s[0,10].inspect}" end if typ != :space ts << [typ, lexeme, val] end s = s[lexeme.length..-1] end ts end # Scans the first token in s and # returns a 3-element list, or nil # if no such token exists. # # The first list element is one of # '{', '}', ':', ',', '[', ']', # :val, :str, and :space. # # The second element is the lexeme. # # The third element is the value of the # token for :val and :str, otherwise # it is the lexeme. def tok(s) case s[0] when ?{ then ['{', s[0,1], s[0,1]] when ?} then ['}', s[0,1], s[0,1]] when ?: then [':', s[0,1], s[0,1]] when ?, then [',', s[0,1], s[0,1]] when ?[ then ['[', s[0,1], s[0,1]] when ?] then [']', s[0,1], s[0,1]] when ?n then nulltok(s) when ?t then truetok(s) when ?f then falsetok(s) when ?" then strtok(s) when Spc then [:space, s[0,1], s[0,1]] when ?\t then [:space, s[0,1], s[0,1]] when ?\n then [:space, s[0,1], s[0,1]] when ?\r then [:space, s[0,1], s[0,1]] else numtok(s) end end def nulltok(s); s[0,4] == 'null' && [:val, 'null', nil] end def truetok(s); s[0,4] == 'true' && [:val, 'true', true] end def falsetok(s); s[0,5] == 'false' && [:val, 'false', false] end def numtok(s) m = /-?([1-9][0-9]+|[0-9])([.][0-9]+)?([eE][+-]?[0-9]+)?/.match(s) if m && m.begin(0) == 0 if m[3] && !m[2] [:val, m[0], Integer(m[1])*(10**Integer(m[3][1..-1]))] elsif m[2] [:val, m[0], Float(m[0])] else [:val, m[0], Integer(m[0])] end end end def strtok(s) m = /"([^"\\]|\\["\/\\bfnrt]|\\u[0-9a-fA-F]{4})*"/.match(s) if ! m raise Error, "invalid string literal at #{abbrev(s)}" end [:str, m[0], unquote(m[0])] end def abbrev(s) t = s[0,10] p = t['`'] t = t[0,p] if p t = t + '...' if t.length < s.length '`' + t + '`' end # Converts a quoted json string literal q into a UTF-8-encoded string. # The rules are different than for Ruby, so we cannot use eval. # Unquote will raise an error if q contains control characters. def unquote(q) q = q[1...-1] a = q.dup # allocate a big enough string r, w = 0, 0 while r < q.length c = q[r] case true when c == ?\\ r += 1 if r >= q.length raise Error, "string literal ends with a \"\\\": \"#{q}\"" end case q[r] when ?",?\\,?/,?' a[w] = q[r] r += 1 w += 1 when ?b,?f,?n,?r,?t a[w] = Unesc[q[r]] r += 1 w += 1 when ?u r += 1 uchar = begin hexdec4(q[r,4]) rescue RuntimeError => e raise Error, "invalid escape sequence \\u#{q[r,4]}: #{e}" end r += 4 if surrogate? uchar if q.length >= r+6 uchar1 = hexdec4(q[r+2,4]) uchar = subst(uchar, uchar1) if uchar != Ucharerr # A valid pair; consume. r += 6 end end end w += ucharenc(a, w, uchar) else raise Error, "invalid escape char #{q[r]} in \"#{q}\"" end when c == ?", c < Spc raise Error, "invalid character in string literal \"#{q}\"" else # Copy anything else byte-for-byte. # Valid UTF-8 will remain valid UTF-8. # Invalid UTF-8 will remain invalid UTF-8. a[w] = c r += 1 w += 1 end end a[0,w] end # Encodes unicode character u as UTF-8 # bytes in string a at position i. # Returns the number of bytes written. def ucharenc(a, i, u) case true when u <= Uchar1max a[i] = (u & 0xff).chr 1 when u <= Uchar2max a[i+0] = (Utag2 | ((u>>6)&0xff)).chr a[i+1] = (Utagx | (u&Umaskx)).chr 2 when u <= Uchar3max a[i+0] = (Utag3 | ((u>>12)&0xff)).chr a[i+1] = (Utagx | ((u>>6)&Umaskx)).chr a[i+2] = (Utagx | (u&Umaskx)).chr 3 else a[i+0] = (Utag4 | ((u>>18)&0xff)).chr a[i+1] = (Utagx | ((u>>12)&Umaskx)).chr a[i+2] = (Utagx | ((u>>6)&Umaskx)).chr a[i+3] = (Utagx | (u&Umaskx)).chr 4 end end def hexdec4(s) if s.length != 4 raise Error, 'short' end (nibble(s[0])<<12) | (nibble(s[1])<<8) | (nibble(s[2])<<4) | nibble(s[3]) end def subst(u1, u2) if Usurr1 <= u1 && u1 < Usurr2 && Usurr2 <= u2 && u2 < Usurr3 return ((u1-Usurr1)<<10) | (u2-Usurr2) + Usurrself end return Ucharerr end def unsubst(u) if u < Usurrself || u > Umax || surrogate?(u) return Ucharerr, Ucharerr end u -= Usurrself [Usurr1 + ((u>>10)&0x3ff), Usurr2 + (u&0x3ff)] end def surrogate?(u) Usurr1 <= u && u < Usurr3 end def nibble(c) case true when ?0 <= c && c <= ?9 then c.ord - ?0.ord when ?a <= c && c <= ?z then c.ord - ?a.ord + 10 when ?A <= c && c <= ?Z then c.ord - ?A.ord + 10 else raise Error, "invalid hex code #{c}" end end # Encodes x into a json text. It may contain only # Array, Hash, String, Numeric, true, false, nil. # (Note, this list excludes Symbol.) # X itself must be an Array or a Hash. # No other value can be encoded, and an error will # be raised if x contains any other value, such as # Nan, Infinity, Symbol, and Proc, or if a Hash key # is not a String. # Strings contained in x must be valid UTF-8. def encode(x) case x when Hash then objenc(x) when Array then arrenc(x) else raise Error, 'root value must be an Array or a Hash' end end def valenc(x) case x when Hash then objenc(x) when Array then arrenc(x) when String then strenc(x) when Numeric then numenc(x) when true then "true" when false then "false" when nil then "null" else raise Error, "cannot encode #{x.class}: #{x.inspect}" end end def objenc(x) '{' + x.map{|k,v| keyenc(k) + ':' + valenc(v)}.join(',') + '}' end def arrenc(a) '[' + a.map{|x| valenc(x)}.join(',') + ']' end def keyenc(k) case k when String then strenc(k) else raise Error, "Hash key is not a string: #{k.inspect}" end end def strenc(s) t = StringIO.new t.putc(?") r = 0 while r < s.length case s[r] when ?" then t.print('\\"') when ?\\ then t.print('\\\\') when ?\b then t.print('\\b') when ?\f then t.print('\\f') when ?\n then t.print('\\n') when ?\r then t.print('\\r') when ?\t then t.print('\\t') else c = s[r] case true when Spc <= c && c <= ?~ t.putc(c) when true u, size = uchardec(s, r) r += size - 1 # we add one more at the bottom of the loop if u < 0x10000 t.print('\\u') hexenc4(t, u) else u1, u2 = unsubst(u) t.print('\\u') hexenc4(t, u1) t.print('\\u') hexenc4(t, u2) end else # invalid byte; skip it end end r += 1 end t.putc(?") t.string end def hexenc4(t, u) t.putc(Hex[(u>>12)&0xf]) t.putc(Hex[(u>>8)&0xf]) t.putc(Hex[(u>>4)&0xf]) t.putc(Hex[u&0xf]) end def numenc(x) if x.nan? || x.infinite? return 'null' end rescue nil "#{x}" end # Decodes unicode character u from UTF-8 # bytes in string s at position i. # Returns u and the number of bytes read. def uchardec(s, i) n = s.length - i return [Ucharerr, 1] if n < 1 c0 = s[i].ord # 1-byte, 7-bit sequence? if c0 < Utagx return [c0, 1] end # unexpected continuation byte? return [Ucharerr, 1] if c0 < Utag2 # need continuation byte return [Ucharerr, 1] if n < 2 c1 = s[i+1].ord return [Ucharerr, 1] if c1 < Utagx || Utag2 <= c1 # 2-byte, 11-bit sequence? if c0 < Utag3 u = (c0&Umask2)<<6 | (c1&Umaskx) return [Ucharerr, 1] if u <= Uchar1max return [u, 2] end # need second continuation byte return [Ucharerr, 1] if n < 3 c2 = s[i+2].ord return [Ucharerr, 1] if c2 < Utagx || Utag2 <= c2 # 3-byte, 16-bit sequence? if c0 < Utag4 u = (c0&Umask3)<<12 | (c1&Umaskx)<<6 | (c2&Umaskx) return [Ucharerr, 1] if u <= Uchar2max return [u, 3] end # need third continuation byte return [Ucharerr, 1] if n < 4 c3 = s[i+3].ord return [Ucharerr, 1] if c3 < Utagx || Utag2 <= c3 # 4-byte, 21-bit sequence? if c0 < Utag5 u = (c0&Umask4)<<18 | (c1&Umaskx)<<12 | (c2&Umaskx)<<6 | (c3&Umaskx) return [Ucharerr, 1] if u <= Uchar3max return [u, 4] end return [Ucharerr, 1] end class Error < ::StandardError end Utagx = 0x80 # 1000 0000 Utag2 = 0xc0 # 1100 0000 Utag3 = 0xe0 # 1110 0000 Utag4 = 0xf0 # 1111 0000 Utag5 = 0xF8 # 1111 1000 Umaskx = 0x3f # 0011 1111 Umask2 = 0x1f # 0001 1111 Umask3 = 0x0f # 0000 1111 Umask4 = 0x07 # 0000 0111 Uchar1max = (1<<7) - 1 Uchar2max = (1<<11) - 1 Uchar3max = (1<<16) - 1 Ucharerr = 0xFFFD # unicode "replacement char" Usurrself = 0x10000 Usurr1 = 0xd800 Usurr2 = 0xdc00 Usurr3 = 0xe000 Umax = 0x10ffff Spc = ' '[0] Unesc = {?b=>?\b, ?f=>?\f, ?n=>?\n, ?r=>?\r, ?t=>?\t} Hex = '0123456789abcdef' end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/spec_helper.rb
sinatra-contrib/spec/spec_helper.rb
ENV['RACK_ENV'] = 'test' require 'sinatra/contrib' # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause this # file to always be loaded, without a need to explicitly require it in any files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, make a # separate helper file that requires this one and then use it only in the specs # that actually need it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. config.disable_monkey_patching! # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 5 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # Enable only the newer, non-monkey-patching expect syntax. # For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax expectations.syntax = :expect end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Enable only the newer, non-monkey-patching expect syntax. # For more details, see: # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ mocks.syntax = :expect # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended. mocks.verify_partial_doubles = true end config.include Sinatra::TestHelpers end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/spec/required_params_spec.rb
sinatra-contrib/spec/required_params_spec.rb
require_relative 'spec_helper' RSpec.describe Sinatra::RequiredParams do context "#required_params" do context "simple keys" do before do mock_app do helpers Sinatra::RequiredParams get('/') { required_params(:p1, :p2) } end end it 'return 400 if required params do not exist' do get('/') expect(last_response.status).to eq(400) end it 'return 400 if required params do not exist partially' do get('/', :p1 => 1) expect(last_response.status).to eq(400) end it 'return 200 if required params exist' do get('/', :p1 => 1, :p2 => 2) expect(last_response.status).to eq(200) end it 'return 200 if required params exist with array' do get('/', :p1 => 1, :p2 => [31, 32, 33]) expect(last_response.status).to eq(200) end end context "hash keys" do before do mock_app do helpers Sinatra::RequiredParams get('/') { required_params(:p1, :p2 => :p21) } end end it 'return 400 if required params do not exist' do get('/') expect(last_response.status).to eq(400) end it 'return 200 if required params exist' do get('/', :p1 => 1, :p2 => {:p21 => 21}) expect(last_response.status).to eq(200) end it 'return 400 if p2 is not a hash' do get('/', :p1 => 1, :p2 => 2) expect(last_response.status).to eq(400) end end context "complex keys" do before do mock_app do helpers Sinatra::RequiredParams get('/') { required_params(:p1 => [:p11, {:p12 => :p121, :p122 => [:p123, {:p124 => :p1241}]}]) } end end it 'return 400 if required params do not exist' do get('/') expect(last_response.status).to eq(400) end it 'return 200 if required params exist' do get('/', :p1 => {:p11 => 11, :p12 => {:p121 => 121}, :p122 => {:p123 => 123, :p124 => {:p1241 => 1241}}}) expect(last_response.status).to eq(200) end end end context "#_required_params" do it "is invisible" do expect { _required_params }.to raise_error(NameError) end end end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/webdav.rb
sinatra-contrib/lib/sinatra/webdav.rb
# frozen_string_literal: true require 'sinatra/base' module Sinatra # = Sinatra::WebDAV # # This extensions provides WebDAV verbs, as defined by RFC 4918 # (https://tools.ietf.org/html/rfc4918). To use this in your app, # just +register+ it: # # require 'sinatra/base' # require 'sinatra/webdav' # # class Application < Sinatra::Base # register Sinatra::WebDAV # # # Now you can use any WebDAV verb: # propfind '/2014/january/21' do # 'I have a lunch at 9 PM' # end # end # # You can use it in classic application just by requiring the extension: # # require 'sinatra' # require 'sinatra/webdav' # # mkcol '/2015' do # 'You started 2015!' # end # module WebDAV def self.registered(_) Sinatra::Request.include WebDAV::Request end module Request def self.included(base) base.class_eval do alias_method :_safe?, :safe? alias_method :_idempotent?, :idempotent? def safe? _safe? or propfind? end def idempotent? _idempotent? or propfind? or move? or unlock? # or lock? end end end def propfind? request_method == 'PROPFIND' end def proppatch? request_method == 'PROPPATCH' end def mkcol? request_method == 'MKCOL' end def copy? request_method == 'COPY' end def move? request_method == 'MOVE' end # def lock? # request_method == 'LOCK' # end def unlock? request_method == 'UNLOCK' end end def propfind(path, opts = {}, &bk) route 'PROPFIND', path, opts, &bk end def proppatch(path, opts = {}, &bk) route 'PROPPATCH', path, opts, &bk end def mkcol(path, opts = {}, &bk) route 'MKCOL', path, opts, &bk end def copy(path, opts = {}, &bk) route 'COPY', path, opts, &bk end def move(path, opts = {}, &bk) route 'MOVE', path, opts, &bk end # def lock(path, opts = {}, &bk) route 'LOCK', path, opts, &bk end def unlock(path, opts = {}, &bk) route 'UNLOCK', path, opts, &bk end end register WebDAV Delegator.delegate :propfind, :proppatch, :mkcol, :copy, :move, :unlock # :lock end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/cookies.rb
sinatra-contrib/lib/sinatra/cookies.rb
# frozen_string_literal: true require 'sinatra/base' module Sinatra # = Sinatra::Cookies # # Easy way to deal with cookies # # == Usage # # Allows you to read cookies: # # get '/' do # "value: #{cookies[:something]}" # end # # And of course to write cookies: # # get '/set' do # cookies[:something] = 'foobar' # redirect to('/') # end # # And generally behaves like a hash: # # get '/demo' do # cookies.merge! 'foo' => 'bar', 'bar' => 'baz' # cookies.keep_if { |key, value| key.start_with? 'b' } # foo, bar = cookies.values_at 'foo', 'bar' # "size: #{cookies.length}" # end # # === Classic Application # # In a classic application simply require the helpers, and start using them: # # require "sinatra" # require "sinatra/cookies" # # # The rest of your classic application code goes here... # # === Modular Application # # In a modular application you need to require the helpers, and then tell # the application to use them: # # require "sinatra/base" # require "sinatra/cookies" # # class MyApp < Sinatra::Base # helpers Sinatra::Cookies # # # The rest of your modular application code goes here... # end # module Cookies class Jar include Enumerable attr_reader :options def initialize(app) @response_array = nil @response_hash = {} @response = app.response @request = app.request @deleted = [] @options = { path: @request.script_name.to_s.empty? ? '/' : @request.script_name, domain: @request.host == 'localhost' ? nil : @request.host, secure: @request.secure?, httponly: true } return unless app.settings.respond_to? :cookie_options @options.merge! app.settings.cookie_options end def ==(other) other.respond_to? :to_hash and to_hash == other.to_hash end def [](key) response_cookies[key.to_s] || request_cookies[key.to_s] end def []=(key, value) set(key, value: value) end if Hash.method_defined? :assoc def assoc(key) to_hash.assoc(key.to_s) end end def clear each_key { |k| delete(k) } end def compare_by_identity? false end def default nil end alias default_proc default def delete(key) result = self[key] @response.delete_cookie(key.to_s, @options) result end def delete_if return enum_for(__method__) unless block_given? each { |k, v| delete(k) if yield(k, v) } self end def each(&block) return enum_for(__method__) unless block_given? to_hash.each(&block) end def each_key(&block) return enum_for(__method__) unless block_given? to_hash.each_key(&block) end alias each_pair each def each_value(&block) return enum_for(__method__) unless block_given? to_hash.each_value(&block) end def empty? to_hash.empty? end def fetch(key, &block) response_cookies.fetch(key.to_s) do request_cookies.fetch(key.to_s, &block) end end if Hash.method_defined? :flatten def flatten to_hash.flatten end end def has_key?(key) response_cookies.key? key.to_s or request_cookies.key? key.to_s end def has_value?(value) response_cookies.value? value or request_cookies.value? value end def hash to_hash.hash end alias include? has_key? alias member? has_key? def inspect "<##{self.class}: #{to_hash.inspect[1..-2]}>" end if Hash.method_defined? :invert def invert to_hash.invert end end def keep_if return enum_for(__method__) unless block_given? delete_if { |*a| !yield(*a) } end def key(value) to_hash.key(value) end alias key? has_key? def keys to_hash.keys end def length to_hash.length end def merge(other, &block) to_hash.merge(other, &block) end def merge!(other) other.each_pair do |key, value| self[key] = if block_given? && include?(key) yield(key.to_s, self[key], value) else value end end end def rassoc(value) to_hash.rassoc(value) end def rehash response_cookies.rehash request_cookies.rehash self end def reject(&block) return enum_for(__method__) unless block_given? to_hash.reject(&block) end alias reject! delete_if def replace(other) select! { |k, _v| other.include?(k) or other.include?(k.to_s) } merge! other end def select(&block) return enum_for(__method__) unless block_given? to_hash.select(&block) end alias select! keep_if if Hash.method_defined? :select! def set(key, options = {}) @response.set_cookie key.to_s, @options.merge(options) end def shift key, value = to_hash.shift delete(key) [key, value] end alias size length if Hash.method_defined? :sort def sort(&block) to_hash.sort(&block) end end alias store []= def to_hash request_cookies.merge(response_cookies) end def to_a to_hash.to_a end def to_s to_hash.to_s end alias update merge! alias value? has_value? def values to_hash.values end def values_at(*list) list.map { |k| self[k] } end private def warn(message) super "#{caller.first[/^[^:]:\d+:/]} warning: #{message}" end def deleted parse_response @deleted end def response_cookies parse_response @response_hash end def parse_response cookies_from_response = Array(@response['Set-Cookie']) return if @response_array == cookies_from_response hash = {} cookies_from_response.each do |line| key, value = line.split(';', 2).first.to_s.split('=', 2) next if key.nil? key = Rack::Utils.unescape(key) if line =~ /expires=Thu, 01[-\s]Jan[-\s]1970/ @deleted << key else @deleted.delete key hash[key] = value end end @response_hash.replace hash @response_array = cookies_from_response end def request_cookies @request.cookies.reject { |key, _value| deleted.include? key } end end def cookies @cookies ||= Jar.new(self) end end helpers Cookies end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/respond_with.rb
sinatra-contrib/lib/sinatra/respond_with.rb
# frozen_string_literal: true require 'sinatra/json' require 'sinatra/base' module Sinatra # # = Sinatra::RespondWith # # These extensions let Sinatra automatically choose what template to render or # action to perform depending on the request's Accept header. # # Example: # # # Without Sinatra::RespondWith # get '/' do # data = { :name => 'example' } # request.accept.each do |type| # case type.to_s # when 'text/html' # halt haml(:index, :locals => data) # when 'text/json' # halt data.to_json # when 'application/atom+xml' # halt nokogiri(:'index.atom', :locals => data) # when 'application/xml', 'text/xml' # halt nokogiri(:'index.xml', :locals => data) # when 'text/plain' # halt 'just an example' # end # end # error 406 # end # # # With Sinatra::RespondWith # get '/' do # respond_with :index, :name => 'example' do |f| # f.txt { 'just an example' } # end # end # # Both helper methods +respond_to+ and +respond_with+ let you define custom # handlers like the one above for +text/plain+. +respond_with+ additionally # takes a template name and/or an object to offer the following default # behavior: # # * If a template name is given, search for a template called # +name.format.engine+ (+index.xml.nokogiri+ in the above example). # * If a template name is given, search for a templated called +name.engine+ # for engines known to result in the requested format (+index.haml+). # * If a file extension associated with the mime type is known to Sinatra, and # the object responds to +to_extension+, call that method and use the result # (+data.to_json+). # # == Security # # Since methods are triggered based on client input, this can lead to security # issues (but not as severe as those might appear in the first place: keep in # mind that only known file extensions are used). You should limit # the possible formats you serve. # # This is possible with the +provides+ condition: # # get '/', :provides => [:html, :json, :xml, :atom] do # respond_with :index, :name => 'example' # end # # However, since you have to set +provides+ for every route, this extension # adds an app global (class method) `respond_to`, that lets you define content # types for all routes: # # respond_to :html, :json, :xml, :atom # get('/a') { respond_with :index, :name => 'a' } # get('/b') { respond_with :index, :name => 'b' } # # == Custom Types # # Use the +on+ method for defining actions for custom types: # # get '/' do # respond_to do |f| # f.xml { nokogiri :index } # f.on('application/custom') { custom_action } # f.on('text/*') { data.to_s } # f.on('*/*') { "matches everything" } # end # end # # Definition order does not matter. module RespondWith class Format def initialize(app) @app = app @map = {} @generic = {} @default = nil end def on(type, &block) @app.settings.mime_types(type).each do |mime| case mime when '*/*' then @default = block when %r{^([^/]+)/\*$} then @generic[$1] = block else @map[mime] = block end end end def finish yield self if block_given? mime_type = @app.content_type || @app.request.preferred_type(@map.keys) || @app.request.preferred_type || 'text/html' type = mime_type.split(/\s*;\s*/, 2).first handlers = [@map[type], @generic[type[%r{^[^/]+}]], @default].compact handlers.each do |block| if (result = block.call(type)) @app.content_type mime_type @app.halt result end end @app.halt 500, 'Unknown template engine' end def method_missing(method, *args, &block) return super if args.any? || block.nil? || !@app.mime_type(method) on(method, &block) end end module Helpers include Sinatra::JSON def respond_with(template, object = nil, &block) unless Symbol === template object = template template = nil end format = Format.new(self) format.on '*/*' do |type| exts = settings.ext_map[type] exts << :xml if type.end_with? '+xml' if template args = template_cache.fetch(type, template) { template_for(template, exts) } if args.any? locals = { object: object } locals.merge! object.to_hash if object.respond_to? :to_hash renderer = args.first options = args[1..] + [{ locals: locals }] halt send(renderer, *options) end end if object exts.each do |ext| halt json(object) if ext == :json next unless object.respond_to? method = "to_#{ext}" halt(*object.send(method)) end end false end format.finish(&block) end def respond_to(&block) Format.new(self).finish(&block) end private def template_for(name, exts) # in production this is cached, so don't worry too much about runtime possible = [] settings.template_engines[:all].each do |engine| exts.each { |ext| possible << [engine, "#{name}.#{ext}"] } end exts.each do |ext| settings.template_engines[ext].each { |e| possible << [e, name] } end possible.each do |engine, template| klass = Tilt.default_mapping.template_map[engine.to_s] || Tilt.lazy_map[engine.to_s].fetch(0, [])[0] find_template(settings.views, template, klass) do |file| next unless File.exist? file return settings.rendering_method(engine) << template.to_sym end end [] # nil or false would not be cached end end def remap_extensions ext_map.clear Rack::Mime::MIME_TYPES.each { |e, t| ext_map[t] << e[1..].to_sym } ext_map['text/javascript'] << 'js' ext_map['text/xml'] << 'xml' end def mime_type(*) result = super remap_extensions result end def respond_to(*formats) @respond_to ||= nil if formats.any? @respond_to ||= [] @respond_to.concat formats elsif @respond_to.nil? && superclass.respond_to?(:respond_to) superclass.respond_to else @respond_to end end def rendering_method(engine) return [engine] if Sinatra::Templates.method_defined? engine return [:mab] if engine.to_sym == :markaby %i[render engine] end private def compile!(verb, path, block, **options) options[:provides] ||= respond_to if respond_to super end def self.jrubyify(engs) not_supported = [:markdown] engs.each_key do |key| engs[key].collect! { |eng| eng == :yajl ? :json_pure : eng } engs[key].delete_if { |eng| not_supported.include?(eng) } end engs end def self.engines engines = { css: %i[sass scss], xml: %i[builder nokogiri], html: %i[erb erubi haml hamlit slim liquid mab markdown rdoc], all: (Sinatra::Templates.instance_methods.map(&:to_sym) + [:mab] - %i[find_template markaby]), json: [:yajl] } engines.default = [] defined?(JRUBY_VERSION) ? jrubyify(engines) : engines end def self.registered(base) base.set :ext_map, Hash.new { |h, k| h[k] = [] } base.set :template_engines, engines base.remap_extensions base.helpers Helpers end end register RespondWith Delegator.delegate :respond_to end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/required_params.rb
sinatra-contrib/lib/sinatra/required_params.rb
# frozen_string_literal: true require 'sinatra/base' module Sinatra # = Sinatra::RequiredParams # # Ensure required query parameters # # == Usage # # Set required query parameter keys in the argument. # It'll halt with 400 if required keys don't exist. # # get '/simple_keys' do # required_params :p1, :p2 # end # # Complicated pattern is also fine. # # get '/complicated_keys' do # required_params :p1, :p2 => [:p3, :p4] # end # # === Classic Application # # In a classic application simply require the helpers, and start using them: # # require "sinatra" # require "sinatra/required_params" # # # The rest of your classic application code goes here... # # === Modular Application # # In a modular application you need to require the helpers, and then tell # the application to use them: # # require "sinatra/base" # require "sinatra/required_params" # # class MyApp < Sinatra::Base # helpers Sinatra::RequiredParams # # # The rest of your modular application code goes here... # end # module RequiredParams def required_params(*keys) _required_params(params, *keys) end private def _required_params(p, *keys) keys.each do |key| if key.is_a?(Hash) _required_params(p, *key.keys) key.each do |k, v| _required_params(p[k.to_s], v) end elsif key.is_a?(Array) _required_params(p, *key) else halt 400 unless p.respond_to?(:key?) && p&.key?(key.to_s) end end true end end helpers RequiredParams end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false
sinatra/sinatra
https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/engine_tracking.rb
sinatra-contrib/lib/sinatra/engine_tracking.rb
# frozen_string_literal: true require 'sinatra/base' module Sinatra # Adds methods like `haml?` that allow helper methods to check whether they # are called from within a template. module EngineTracking attr_reader :current_engine # @return [Boolean] Returns true if current engine is `:erb`. def erb? @current_engine == :erb end # Returns true if the current engine is `:erubi`, or `Tilt[:erb]` is set # to Tilt::ErubiTemplate. # # @return [Boolean] Returns true if current engine is `:erubi`. def erubi? @current_engine == :erubi or (erb? && Tilt[:erb] == Tilt::ErubiTemplate) end # @return [Boolean] Returns true if current engine is `:haml`. def haml? @current_engine == :haml end # @return [Boolean] Returns true if current engine is `:sass`. def sass? @current_engine == :sass end # @return [Boolean] Returns true if current engine is `:scss`. def scss? @current_engine == :scss end # @return [Boolean] Returns true if current engine is `:builder`. def builder? @current_engine == :builder end # @return [Boolean] Returns true if current engine is `:liquid`. def liquid? @current_engine == :liquid end # @return [Boolean] Returns true if current engine is `:markdown`. def markdown? @current_engine == :markdown end # @return [Boolean] Returns true if current engine is `:rdoc`. def rdoc? @current_engine == :rdoc end # @return [Boolean] Returns true if current engine is `:markaby`. def markaby? @current_engine == :markaby end # @return [Boolean] Returns true if current engine is `:nokogiri`. def nokogiri? @current_engine == :nokogiri end # @return [Boolean] Returns true if current engine is `:slim`. def slim? @current_engine == :slim end # @return [Boolean] Returns true if current engine is `:ruby`. def ruby? @current_engine == :ruby end def initialize(*) @current_engine = :ruby super end # @param engine [Symbol, String] Name of Engine to shift to. def with_engine(engine) engine_was = @current_engine @current_engine = engine.to_sym yield ensure @current_engine = engine_was end private def render(engine, *) with_engine(engine) { super } end end helpers EngineTracking end
ruby
MIT
074d876e0c54ffbe605bb733cefc5a71bb22dbc1
2026-01-04T15:37:42.068011Z
false