CodeSampleX

Exemple

sinatra 4.2.1: Test a Sinatra 4 app with rack-test in the same process, with no server, and get the params, filter and 404 behaviour right instead of guessing it

Échantillon vérifié pour gem sinatra 4.2.1: Test a Sinatra 4 app with rack-test in the same process, with no server, and get the params, filter and 404…

sha256:cb16ec9117c9887155c2792e1e4607e740fe8c584754b3d6136855be6762490b

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
2
Environnement déclaré ruby 3 linux x64 ruby 3 ruby bundler

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
ruby 3 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · gem@1
2026-08-14
ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · gem@1
2026-08-18

Cas

HOW
Objectif
Test a Sinatra 4 app with rack-test in the same process, with no server, and get the params, filter and 404 behaviour right instead of guessing it
Paquets
Symboles
  • Sinatra::Base
  • Sinatra::IndifferentHash
  • Sinatra::NotFound
  • Sinatra::Base#halt
  • Sinatra::Base#params
  • Rack::Test::Methods
  • Rack::Test::Session
  • Rack::Protection::HostAuthorization
  • Rack::Headers
Environnement
ruby 3
Créé
2026-08-14T20:46:51Z

Contrat

  1. assert a modular Sinatra::Base app never starts a server, while the classic Sinatra::Application would
  2. assert the environment behind these measurements is development, read out of ENV when sinatra/base was required
  3. assert a default Sinatra 4 app answers rack-test's Host of example.org with a 403 whose body is Host not permitted
  4. assert a Host of localhost, anything under .test, and any IP literal are accepted by that same development list
  5. assert an empty permitted_hosts switches the check off and the identical request then reaches the route
  6. assert a named parameter arrives as a String under its own key, with no splat key present at all
  7. assert params is a Sinatra::IndifferentHash where the symbol and the string reach the same value
  8. assert a splat arrives as an Array under splat even when it matched exactly once, while the block argument is the plain String
  9. assert a splat crosses slashes, that two splats fill the array in order, and that /files/* does not match /files
  10. assert a route capture overrides a query parameter of the same name
  11. assert a query string and a form body merge into params and the form body wins a collision, while request.GET and request.POST stay separate
  12. assert a route capture beats the form body as well, so precedence is route, then form, then query
  13. assert params loses its route captures again once the route returns, while the query parameters stay
  14. assert an unmatched path returns Sinatra's own 404 page naming the app class, rather than an empty body
  15. assert halt 404 inside a matched route is the 404 that really is empty
  16. assert a JSON-looking string body is served as text/html;charset=utf-8 until content_type is declared, and the body is passed through untouched
  17. assert the response header names come back lowercase under Rack 3
  18. assert return inside a before filter leaves only that filter, so the second filter and the route still run and the client gets a 200
  19. assert halt inside a before filter stops the second filter and the route and owns the status and body
  20. assert after filters still run on a halted request

Fichiers

  • Gemfile
  • Gemfile.lock
  • csx.json
  • src/app.rb
  • test/contract.rb

Télécharger l’artefact source (tar.gz)

Code source

Gemfile
source "https://rubygems.org"

# Checked for native extensions before pinning, because the image this is
# measured in (ruby:3-alpine) ships no C compiler: every gem here has to be
# pure Ruby or `bundle install` dies in extconf.
#
# sinatra 4.2.1 pulls logger, mustermann, rack, rack-protection, rack-session
# and tilt. All pure Ruby, all install with no toolchain — measured, the whole
# closure resolves and installs on alpine.
gem "sinatra", "4.2.1"

# rack-test 2.2.0 depends only on rack, also pure Ruby. It drives the app
# through Rack directly, so nothing here binds a port.
gem "rack-test", "2.2.0"

# minitest 6 is the newest release but is unusable here: 6.x added runtime
# dependencies on drb and prism (~> 1.5), and prism compiles a C extension.
# 5.27.0 is the newest that installs in this image.
gem "minitest", "5.27.0"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    base64 (0.3.0)
    logger (1.7.0)
    minitest (5.27.0)
    mustermann (3.1.1)
    rack (3.2.7)
    rack-protection (4.2.1)
      base64 (>= 0.1.0)
      logger (>= 1.6.0)
      rack (>= 3.0.0, < 4)
    rack-session (2.1.2)
      base64 (>= 0.1.0)
      rack (>= 3.0.0)
    rack-test (2.2.0)
      rack (>= 1.3)
    sinatra (4.2.1)
      logger (>= 1.6.0)
      mustermann (~> 3.0)
      rack (>= 3.0.0, < 4)
      rack-protection (= 4.2.1)
      rack-session (>= 2.0.0, < 3)
      tilt (~> 2.0)
    tilt (2.8.0)

PLATFORMS
  ruby
  x86_64-linux-musl

DEPENDENCIES
  minitest (= 5.27.0)
  rack-test (= 2.2.0)
  sinatra (= 4.2.1)

CHECKSUMS
  base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b
  bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
  logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
  minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5
  mustermann (3.1.1) sha256=4c6170c7234d5499c345562ba7c7dfe73e1754286dcc1abb053064d66a127198
  rack (3.2.7) sha256=93e13e1c24f93556671d85d2d79fa228c3485815c50d7e2f265b5330c6528fb7
  rack-protection (4.2.1) sha256=cf6e2842df8c55f5e4d1a4be015e603e19e9bc3a7178bae58949ccbb58558bac
  rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8
  rack-test (2.2.0) sha256=005a36692c306ac0b4a9350355ee080fd09ddef1148a5f8b2ac636c720f5c463
  sinatra (4.2.1) sha256=b7aeb9b11d046b552972ade834f1f9be98b185fa8444480688e3627625377080
  tilt (2.8.0) sha256=ba472eb2716fe1e04112d6d219a9dae938ec09a6a1e2ad3ecc7922e79bde3721

BUNDLED WITH
  4.0.18
csx.json
{"case":{"caseId":"case:sha256:86a2e6f751f0f79c03829ea3ea3822bda3bfc95a5abdaaad7bfbb1d5863659c7","constraints":{"runtime":"ruby"},"contract":["assert a modular Sinatra::Base app never starts a server, while the classic Sinatra::Application would","assert the environment behind these measurements is development, read out of ENV when sinatra/base was required","assert a default Sinatra 4 app answers rack-test's Host of example.org with a 403 whose body is Host not permitted","assert a Host of localhost, anything under .test, and any IP literal are accepted by that same development list","assert an empty permitted_hosts switches the check off and the identical request then reaches the route","assert a named parameter arrives as a String under its own key, with no splat key present at all","assert params is a Sinatra::IndifferentHash where the symbol and the string reach the same value","assert a splat arrives as an Array under splat even when it matched exactly once, while the block argument is the plain String","assert a splat crosses slashes, that two splats fill the array in order, and that /files/* does not match /files","assert a route capture overrides a query parameter of the same name","assert a query string and a form body merge into params and the form body wins a collision, while request.GET and request.POST stay separate","assert a route capture beats the form body as well, so precedence is route, then form, then query","assert params loses its route captures again once the route returns, while the query parameters stay","assert an unmatched path returns Sinatra's own 404 page naming the app class, rather than an empty body","assert halt 404 inside a matched route is the 404 that really is empty","assert a JSON-looking string body is served as text/html;charset=utf-8 until content_type is declared, and the body is passed through untouched","assert the response header names come back lowercase under Rack 3","assert return inside a before filter leaves only that filter, so the second filter and the route still run and the client gets a 200","assert halt inside a before filter stops the second filter and the route and owns the status and body","assert after filters still run on a halted request"],"goal":"Test a Sinatra 4 app with rack-test in the same process, with no server, and get the params, filter and 404 behaviour right instead of guessing it","kind":"HOW","packages":["pkg:gem/sinatra@4.2.1","pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7","pkg:gem/rack-protection@4.2.1","pkg:gem/mustermann@3.1.1"],"schemaVersion":1,"symbols":["Sinatra::Base","Sinatra::IndifferentHash","Sinatra::NotFound","Sinatra::Base#halt","Sinatra::Base#params","Rack::Test::Methods","Rack::Test::Session","Rack::Protection::HostAuthorization","Rack::Headers"]},"contractCommand":["bundle","exec","ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"bundler","runtime":"ruby","runtimeVersion":"3","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/sinatra@4.2.1","pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7","pkg:gem/rack-protection@4.2.1","pkg:gem/mustermann@3.1.1"],"schemaVersion":1,"symbols":["Sinatra::Base","Sinatra::IndifferentHash","Sinatra::NotFound","Sinatra::Base#halt","Sinatra::Base#params","Rack::Test::Methods","Rack::Test::Session","Rack::Protection::HostAuthorization","Rack::Headers"],"verifierAdapter":"gem@1"}
src/app.rb
# Driving a Sinatra app from a test with rack-test: no server, no port, no
# socket. rack-test calls the Rack app in-process, so everything Sinatra puts
# between Rack and your block — host authorization, filters, the pattern
# matcher, the params merge — still runs for real. That is the point, and it
# is also where the surprises come from.
#
# What this measures, roughly in the order of how much time each one costs
# people:
#
#   1. Sinatra 4 in development answers 403 "Host not permitted" to rack-test's
#      default Host of example.org, before any route runs. Nothing in the 403
#      mentions Sinatra or the setting that produced it.
#   2. params is one hash holding three different things — route captures,
#      the query string, the form body — and the merge order is not the one
#      most people guess.
#   3. A named parameter is a String under its own key; a splat is an Array
#      under "splat", even when it matched exactly once.
#   4. halt and return are not two spellings of the same thing inside a filter.
#   5. The response body of a 404 depends on the environment Sinatra read out
#      of ENV when sinatra/base was required, not on what the app sets later.
#
# require "sinatra/base" + a subclass is the "modular" style, and it is what
# keeps a test run from booting a web server: the classic top-level DSL
# (require "sinatra") registers an at_exit hook that starts one.

require "sinatra/base"

# The routes stash what they saw here. rack-test runs the app inside the test
# process, so the contract reads these back directly instead of inventing a
# serialisation and asserting on a parsed body.
module Capture
  class << self
    attr_accessor :snapshot, :live, :block_args, :rack_get, :rack_post
  end
end

# Filters and the route append to this so the contract can see exactly how far
# a request got.
TRACE = []

class RoutesApp < Sinatra::Base
  # Without this every request below is a 403. Sinatra 4 mounts
  # Rack::Protection::HostAuthorization, and in development the permitted list
  # is localhost, .localhost, .test and any IP literal — rack-test sends
  # Host: example.org, which is on none of them. An empty permitted_hosts
  # turns the check off (rack-protection returns early when the list is
  # empty); APP_ENV=test does the same thing by making the setting {}.
  set :host_authorization, permitted_hosts: []

  # A named parameter. The capture lands under its own key as a String.
  get "/users/:id" do
    # params.dup is deliberate: Sinatra deletes the route captures out of the
    # live hash again once the route returns, so a stashed reference does not
    # show what the route saw. The contract asserts both.
    Capture.snapshot = params.dup
    Capture.live = params
    "named"
  end

  # A splat. The block argument is the matched String; params carries an Array.
  get "/files/*" do |path|
    Capture.snapshot = params.dup
    Capture.live = params
    Capture.block_args = [path]
    "splat"
  end

  get "/say/*/to/*" do |a, b|
    Capture.snapshot = params.dup
    Capture.block_args = [a, b]
    "two splats"
  end

  get "/download/*.*" do
    Capture.snapshot = params.dup
    "extension splat"
  end

  # Query string and form body land in the same params. request.GET and
  # request.POST are captured too, because the merge that decides a collision
  # happens in Rack, not in Sinatra.
  post "/merge" do
    Capture.snapshot = params.dup
    Capture.rack_get = request.GET.dup
    Capture.rack_post = request.POST.dup
    "merged"
  end

  # Same collision with a route capture added on top.
  post "/merge/:field" do
    Capture.snapshot = params.dup
    "merged"
  end

  # A body that any human would call JSON. Sinatra does not look at it.
  get "/looks-like-json" do
    '{"ok":true}'
  end

  get "/declared-json" do
    content_type :json
    '{"ok":true}'
  end

  # halt with a status and nothing else. This is the 404 that really is empty,
  # and it is the contrast that makes Sinatra's own 404 page worth knowing
  # about: an unmatched path does not come out of here.
  get "/halted" do
    halt 404
  end
end

# Two before filters, a route and an after filter, all appending to TRACE, so
# "halt stops the chain and return does not" is a list comparison rather than
# an opinion. The filters are declared with a path so the other apps' requests
# cannot pollute the trace.
class FilterApp < Sinatra::Base
  set :host_authorization, permitted_hosts: []

  before "/guarded" do
    TRACE << :filter_1_entered
    # halt throws :halt. Sinatra catches it outside the whole filter+route
    # chain, so the second filter and the route never run.
    halt 401, "stopped in filter 1" if params["stop"] == "halt"
    # Sinatra compiles each filter block into a method with define_method, so
    # return leaves that one method and nothing else. It reads like an early
    # exit from the request and is only an early exit from this filter.
    return if params["stop"] == "return"

    TRACE << :filter_1_completed
  end

  before "/guarded" do
    TRACE << :filter_2_ran
  end

  get "/guarded" do
    TRACE << :route_ran
    "route body"
  end

  # after filters live in an ensure, so they run even on the halted request.
  after "/guarded" do
    TRACE << :after_filter_ran
  end
end

# Identical to RoutesApp except that it keeps Sinatra's default
# host_authorization, which is what a new app has.
class DefaultHostApp < Sinatra::Base
  get "/ping" do
    "pong"
  end
end
test/contract.rb
require "minitest/autorun"
require "rack/test"
require_relative "../src/app"

# Everything below runs the app in this process. Nothing binds a port, and the
# suite passes with the network switched off entirely.
class SinatraStaysInProcessContract < Minitest::Test
  def test_a_modular_app_never_starts_a_server
    # The classic style — require "sinatra" and define routes at the top
    # level — sets run to !test?, and requiring the file installs an at_exit
    # hook that boots a server with that setting. In development that is on,
    # which is how a test run ends up listening on 4567. Subclassing
    # Sinatra::Base is what turns it off, and it is off for the app itself,
    # not merely for this test.
    refute Sinatra::Base.run?
    refute RoutesApp.run?
    assert Sinatra::Application.run?
  end

  def test_the_environment_these_measurements_were_taken_in
    # Sinatra reads the environment once, out of APP_ENV or RACK_ENV, while
    # sinatra/base is being required. Neither is set here, so it is
    # development — and two of the measurements below (the 403 and the 404
    # body) exist only in development. An app that sets :environment later
    # does not move them: they were decided at require time.
    assert_equal :development, Sinatra::Base.environment
    assert_equal :development, RoutesApp.environment
  end
end

class SinatraHostAuthorizationContract < Minitest::Test
  include Rack::Test::Methods

  def app = DefaultHostApp

  def test_a_default_sinatra_4_app_rejects_rack_tests_host_with_403
    # The first wall people hit. rack-test sends Host: example.org and
    # Sinatra 4 mounts Rack::Protection::HostAuthorization, whose development
    # list is localhost, .localhost, .test and any IP literal. The route is
    # never reached, so this looks like a routing bug: 403 with a body that
    # names neither Sinatra nor the setting, and it appears the day you
    # upgrade to Sinatra 4 rather than the day you write the test.
    get "/ping"

    assert_equal 403, last_response.status
    assert_equal "Host not permitted", last_response.body
    assert_equal "text/plain", last_response.content_type
  end

  def test_a_host_on_the_development_list_gets_through_untouched
    # Three fixes, all measured. Send a Host the list already permits...
    header "Host", "localhost"
    get "/ping"
    assert_equal 200, last_response.status
    assert_equal "pong", last_response.body

    # ...anything under .test, since a leading dot means "and subdomains"...
    header "Host", "app.test"
    get "/ping"
    assert_equal 200, last_response.status

    # ...or any IP literal, because the list carries 0.0.0.0/0 and ::/0.
    header "Host", "127.0.0.1"
    get "/ping"
    assert_equal 200, last_response.status
  end

  def test_an_empty_permitted_hosts_switches_the_check_off
    # The fix that does not depend on what the test harness sends: an empty
    # permitted_hosts makes rack-protection accept every request. Running the
    # suite under APP_ENV=test reaches the same place by a different road,
    # because outside development the whole setting is {}.
    assert_equal({ permitted_hosts: [] }, RoutesApp.host_authorization)

    session = Rack::Test::Session.new(RoutesApp)
    session.get "/users/7"
    assert_equal 200, session.last_response.status
  end
end

class SinatraParamsContract < Minitest::Test
  include Rack::Test::Methods

  def app = RoutesApp

  def test_a_named_parameter_is_a_string_under_its_own_key
    get "/users/7"

    assert_equal 200, last_response.status
    assert_equal "7", Capture.snapshot["id"]
    assert_instance_of String, Capture.snapshot["id"]
    assert_equal ["id"], Capture.snapshot.keys
    # No "splat" key exists on a route that has no splat, so code that reaches
    # for params["splat"] first gets nil rather than an empty list.
    refute Capture.snapshot.key?("splat")
  end

  def test_params_is_indifferent_so_the_symbol_works_too
    get "/users/7"

    # Sinatra::IndifferentHash, not Hash: string and symbol reach the same
    # value. It is still a String-keyed hash underneath, which is why keys
    # comes back as strings.
    assert_instance_of Sinatra::IndifferentHash, Capture.snapshot
    assert_equal "7", Capture.snapshot[:id]
    assert_equal ["id"], Capture.snapshot.keys
  end

  def test_a_splat_is_an_array_under_splat_even_when_it_matched_once
    get "/files/report.csv"

    # The asymmetry with a named parameter, and the reason a splat route that
    # was working suddenly interpolates as ["thing"]: one match still arrives
    # as a one-element Array, and it is filed under "splat" rather than under
    # any name you chose. The block argument is the plain String.
    assert_equal ["report.csv"], Capture.snapshot["splat"]
    assert_instance_of Array, Capture.snapshot["splat"]
    assert_equal ["splat"], Capture.snapshot.keys
    assert_equal ["report.csv"], Capture.block_args
  end

  def test_a_splat_swallows_slashes
    # * is not the single-segment wildcard it is in a shell glob or in most
    # router libraries: it crosses / happily, so /files/* also owns every
    # path below it. Sinatra has no separate ** for this.
    get "/files/a/b/c.txt"
    assert_equal ["a/b/c.txt"], Capture.snapshot["splat"]

    # It stops being greedy where the pattern says so. Two splats fill the
    # array in order, and the last one here matches only the extension
    # because the literal dot has to be matched too.
    get "/say/hello/to/world"
    assert_equal %w[hello world], Capture.snapshot["splat"]
    assert_equal %w[hello world], Capture.block_args

    get "/download/path/to/file.xml"
    assert_equal ["path/to/file", "xml"], Capture.snapshot["splat"]
  end

  def test_a_splat_still_needs_something_to_match
    # /files/* is not a match for /files, so the catch-all route people write
    # to serve a section index does not serve the index itself.
    get "/files"
    assert_equal 404, last_response.status
  end

  def test_the_route_capture_wins_over_a_query_parameter_of_the_same_name
    # params merges the query first and the route captures over the top, so
    # a client cannot forge :id by adding ?id= to the URL. Worth knowing in
    # the other direction too: a query parameter is silently unreachable
    # whenever the route names the same key.
    get "/users/7?id=99&extra=x"

    assert_equal "7", Capture.snapshot["id"]
    assert_equal "x", Capture.snapshot["extra"]
  end

  def test_a_query_string_and_a_form_body_merge_and_the_form_wins
    # Both halves are present, so a POST that also carries a query string is
    # not a bug you need to defend against — but on a collision the form body
    # overwrites the query. The merge happens in Rack::Request#params, which
    # is GET.merge(POST); Sinatra copies the result into params and then lays
    # its route captures on top.
    post "/merge?shared=from-query&only_query=q", { "shared" => "from-form", "only_form" => "f" }

    assert_equal 200, last_response.status
    assert_equal "from-form", Capture.snapshot["shared"]
    assert_equal "q", Capture.snapshot["only_query"]
    assert_equal "f", Capture.snapshot["only_form"]

    # The two halves are still available unmerged, which is the only way to
    # tell where a value came from.
    assert_equal({ "shared" => "from-query", "only_query" => "q" }, Capture.rack_get)
    assert_equal({ "shared" => "from-form", "only_form" => "f" }, Capture.rack_post)
  end

  def test_a_route_capture_beats_the_form_body_as_well
    # Full precedence, measured end to end: route capture, then form body,
    # then query string.
    post "/merge/from-route?field=from-query", { "field" => "from-form" }

    assert_equal "from-route", Capture.snapshot["field"]
    assert_equal ["field"], Capture.snapshot.keys
  end

  def test_params_loses_the_route_captures_once_the_route_returns
    # Not a quirk of this test setup: Sinatra merges the captures into the
    # live params hash for the duration of the route and deletes them again
    # in an ensure. Anything that reads params after the block is finished —
    # a lazy enumerator, a stashed reference, a background job handed
    # params — sees the request without its route captures, while the query
    # parameters are still there. Hand work a copy, not params.
    get "/files/a/b/c.txt?q=1"

    assert_equal ["a/b/c.txt"], Capture.snapshot["splat"]
    assert_equal "1", Capture.snapshot["q"]

    refute Capture.live.key?("splat")
    assert_equal "1", Capture.live["q"]
  end

  def test_an_unmatched_path_gets_sinatras_own_404_page_not_an_empty_body
    get "/nope"

    assert_equal 404, last_response.status
    refute_empty last_response.body
    assert_equal "text/html;charset=utf-8", last_response.content_type
    # In development an unmatched path raises Sinatra::NotFound and hits an
    # error handler Sinatra registers on itself, which renders a page telling
    # you to write the route — including the class name of the app that
    # missed. A test asserting an empty 404 body fails here for a reason that
    # has nothing to do with the app.
    assert_includes last_response.body, "know this ditty"
    assert_includes last_response.body, "class RoutesApp"
    assert Sinatra::Base.errors.key?(Sinatra::NotFound)
  end

  def test_halt_404_is_the_one_that_really_is_empty
    # The contrast that makes the page above worth knowing: halting with a
    # bare status never goes near the NotFound handler, so this 404 is the
    # empty one. Same status, completely different body, and which one a test
    # gets depends on whether the route matched at all.
    get "/halted"

    assert_equal 404, last_response.status
    assert_equal "", last_response.body
  end

  def test_the_content_type_is_text_html_even_for_a_json_looking_body
    # Sinatra does not sniff the body. A route that returns a JSON string and
    # forgets content_type serves it as HTML, and every client that switches
    # on the content type — including a rack-test assertion on
    # last_response.content_type — reads it as HTML. The body itself is
    # passed through untouched, so the mistake is invisible until something
    # downstream refuses to parse it.
    get "/looks-like-json"

    assert_equal "text/html;charset=utf-8", last_response.content_type
    assert_equal '{"ok":true}', last_response.body

    # Note the exact string: no space after the semicolon, and the charset is
    # appended for text types. An assertion on "text/html" alone fails.
    refute_equal "text/html", last_response.content_type
  end

  def test_declaring_the_type_replaces_it_and_adds_no_charset
    get "/declared-json"

    assert_equal "application/json", last_response.content_type
    assert_equal '{"ok":true}', last_response.body
  end

  def test_the_header_names_that_come_back_are_lowercase
    # Rack 3 headers are lowercase by contract. Reading through
    # last_response works either way because Rack::Headers is
    # case-insensitive, but anything that inspects the keys — a header
    # allowlist, a diff of two responses — sees "content-type".
    get "/looks-like-json"

    assert_instance_of Rack::Headers, last_response.headers
    assert_includes last_response.headers.keys, "content-type"
    refute_includes last_response.headers.keys, "Content-Type"
    assert_equal last_response.headers["content-type"], last_response.headers["Content-Type"]
  end
end

class SinatraFilterContract < Minitest::Test
  include Rack::Test::Methods

  def app = FilterApp

  def setup
    TRACE.clear
  end

  def test_without_a_stop_every_filter_and_the_route_run_in_order
    get "/guarded"

    assert_equal 200, last_response.status
    assert_equal "route body", last_response.body
    assert_equal %i[filter_1_entered filter_1_completed filter_2_ran route_ran after_filter_ran], TRACE
  end

  def test_return_leaves_the_filter_and_nothing_else
    # The trap. return inside a before block reads like "stop handling this
    # request", and it stops exactly one thing: the rest of that filter.
    # Sinatra compiles each filter block into a method, so return returns from
    # that method — the second filter still runs, the route still runs, and
    # the client gets a 200 from a request the first filter meant to reject.
    # A guard written this way is not a guard.
    get "/guarded?stop=return"

    assert_equal 200, last_response.status
    assert_equal "route body", last_response.body
    refute_includes TRACE, :filter_1_completed
    assert_equal %i[filter_1_entered filter_2_ran route_ran after_filter_ran], TRACE
  end

  def test_halt_stops_the_rest_of_the_chain_and_owns_the_response
    # halt throws :halt, caught outside the whole before-filter-and-route
    # chain, so the second filter and the route never run and the status and
    # body given to halt are what the client gets.
    get "/guarded?stop=halt"

    assert_equal 401, last_response.status
    assert_equal "stopped in filter 1", last_response.body
    refute_includes TRACE, :filter_2_ran
    refute_includes TRACE, :route_ran
  end

  def test_after_filters_still_run_on_a_halted_request
    # halt is not an exit. after filters sit in an ensure, so cleanup and
    # logging still happen — and so does anything in an after filter that
    # assumes the route ran.
    get "/guarded?stop=halt"

    assert_equal %i[filter_1_entered after_filter_ran], TRACE
  end
end

Seeder d'origine

anonymous