CodeSampleX

Exemplo

rack-test 2.2.0: Manage Rack::Test v2 MockSession unification, removed Methods constants, :query_params separation, forced multipart formatting, dynamic default_host routing, and state restoration

Amostra verificada para gem rack-test 2.2.0: Manage Rack::Test v2 MockSession unification, removed Methods constants, :query_params separation, forced…

sha256:0ca84627ed034a38fb5d367bdf1bb71bdefdffd4b364c6984ec932bd3efcc68a

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
2
Chaves de assinatura que o compilaram
1
Ambiente declarado ruby linux x64 ruby ruby rubygems

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
ruby 3 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-16
ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 SKIPPED compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL
CONTAINER_RUN · rubygems@1
2026-08-18

Caso

HOW
Objetivo
Manage Rack::Test v2 MockSession unification, removed Methods constants, :query_params separation, forced multipart formatting, dynamic default_host routing, and state restoration
Pacotes
Símbolos
  • Rack::Test::Session
  • Rack::Test::Methods
  • Rack::Test::Utils
  • Rack::MockSession
  • Rack::Test::Session#restore_state
Ambiente
ruby
Criado
2026-08-16T16:46:41Z

Contrato

  1. assert Rack::Test::Methods::METHODS is undefined raising NameError, requiring rack/mock_session raises LoadError with Rack::MockSession aliased to Session, and :query_params in env appends to the URI query string separately from request body payloads
  2. assert passing :multipart => true or setting a multipart Content-Type forces multipart MIME body construction even for simple Hash params without file uploads
  3. assert defining a default_host method on a test class dynamically overrides unqualified URI host resolution and cookie scoping
  4. assert Session#restore_state executes a block and rolls back all request, response, and cookie jar modifications upon completion
  5. assert internal formatting helpers on Rack::Test::Utils including build_primitive_part and build_file_part are private methods raising NoMethodError

Arquivos

  • Gemfile
  • NOTES.md
  • csx.json
  • src/app.rb
  • test/contract.rb

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

Gemfile
source "https://rubygems.org"

gem "rack-test", "2.2.0"
gem "rack", "3.2.7"
gem "minitest", "5.27.0"
NOTES.md
# Notes on `pkg:gem/rack-test` Version 2 Contracts

## 1. What `search_known_solution` answered
`search_known_solution` returned three existing samples:
- `sha256:b6e08189aff9762145b13c9da3005e5280f936fd2c9e33822f7436a47fdc8cea` ("Manage Rack::Test per-request CGI environment keys, session header persistence, JSON string Content-Type defaults, UploadedFile multipart symbol params, and redirect method preservation")
- `sha256:5e6ad6f64fb23b10442b9867c77cd2600b9b4f64391a51a71c223bc4a3fe78f3` ("Manage Rack::Test type serialization boundaries across JSON Hash payloads, query parameter type coercion, multipart symbol keys, and CookieJar security scopes")
- `sha256:cb16ec9117c9887155c2792e1e4607e740fe8c584754b3d6136855be6762490b` ("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")

This contract explores major version 2 architectural changes and traps:
- Removal of `Rack::Test::Methods::METHODS` constant and `require "rack/mock_session"`.
- Direct aliasing of `Rack::MockSession` to `Rack::Test::Session`.
- Independent `:query_params` environment key routing for non-GET requests.
- Forced multipart body construction via `:multipart => true` and `CONTENT_TYPE => multipart/*` for standard Hash parameters.
- Dynamic `default_host` method hooks in test classes including `Rack::Test::Methods`.
- Isolated test step execution with state rollback using `Rack::Test::Session#restore_state`.
- Visibility encapsulation of internal formatting helpers in `Rack::Test::Utils`.

## 2. What a model would have written instead
- Assumed `Rack::Test::Methods::METHODS` is available to introspect supported HTTP verbs.
- Attempted `require "rack/mock_session"` to instantiate a mock session.
- Embedded query string parameters directly into POST/PUT URI strings (e.g. `post("/submit?page=2", { "field" => "val" })`) believing `Rack::Test` has no environment mechanism to pass separate query parameters.
- Assumed `post` with `header "Content-Type", "multipart/form-data"` or `:multipart => true` only creates multipart bodies when an `UploadedFile` object is present in parameters.
- Assumed modifying the default host requires mutating `Rack::Test::DEFAULT_HOST` globally rather than defining `default_host` on the test class.
- Manually recorded and restored cookie jar state and last response when running temporary nested request blocks.
- Called `Rack::Test::Utils.build_primitive_part` or `Rack::Test::Utils.build_file_part` directly.

## 3. How the wrong version fails
- **Loud failures**:
  - Referencing `Rack::Test::Methods::METHODS` raises `NameError: uninitialized constant Rack::Test::Methods::METHODS` in version 2.x.
  - Calling `require "rack/mock_session"` raises `LoadError: cannot load such file -- rack/mock_session` in version 2.1+.
  - Calling `Rack::Test::Utils.build_primitive_part` raises `NoMethodError: private method 'build_primitive_part' called for Rack::Test::Utils:Module`.
- **Silent failures with green build**:
  - In version 1.x, passing `:query_params => { ... }` in `env` was silently ignored as an unhandled environment key; the query string remained empty and the application received no query parameters.
  - In version 1.x, passing `header "Content-Type", "multipart/form-data"` without an `UploadedFile` silently formatted parameters as `application/x-www-form-urlencoded`, generating mismatched MIME headers and body payloads.
csx.json
{"case":{"believed":"Rack::Test::Methods exports a METHODS constant of HTTP verbs, standalone session setup requires requiring rack/mock_session, and query parameters cannot be supplied separately from request body params in non-GET requests via env.","caseId":"case:sha256:5f6e357004d531bf82dea26afe91643df2e6fc13757cc8b46182d06dcf6c02f4","contract":["assert Rack::Test::Methods::METHODS is undefined raising NameError, requiring rack/mock_session raises LoadError with Rack::MockSession aliased to Session, and :query_params in env appends to the URI query string separately from request body payloads","assert passing :multipart =\u003e true or setting a multipart Content-Type forces multipart MIME body construction even for simple Hash params without file uploads","assert defining a default_host method on a test class dynamically overrides unqualified URI host resolution and cookie scoping","assert Session#restore_state executes a block and rolls back all request, response, and cookie jar modifications upon completion","assert internal formatting helpers on Rack::Test::Utils including build_primitive_part and build_file_part are private methods raising NoMethodError"],"goal":"Manage Rack::Test v2 MockSession unification, removed Methods constants, :query_params separation, forced multipart formatting, dynamic default_host routing, and state restoration","kind":"HOW","packages":["pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7"],"schemaVersion":1,"symbols":["Rack::Test::Session","Rack::Test::Methods","Rack::Test::Utils","Rack::MockSession","Rack::Test::Session#restore_state"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"rubygems","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7"],"schemaVersion":1,"symbols":["Rack::Test::Session","Rack::Test::Methods","Rack::Test::Utils","Rack::MockSession","Rack::Test::Session#restore_state"],"verifierAdapter":"rubygems@1"}
src/app.rb
# frozen_string_literal: true

require "rack"
require "json"

module RackTestV2Contract
  class RecordingApp
    attr_reader :last_recorded

    def initialize
      @last_recorded = nil
    end

    def call(env)
      req = Rack::Request.new(env)
      raw_body = ""
      if env["rack.input"]
        raw_body = env["rack.input"].read
        env["rack.input"].rewind
      end

      @last_recorded = {
        method: req.request_method,
        scheme: req.scheme,
        host: req.host,
        port: req.port,
        path: req.path_info,
        query_string: req.query_string,
        get_params: req.GET,
        post_params: req.POST,
        params: req.params,
        cookies: req.cookies,
        content_type: req.content_type,
        content_length: req.content_length,
        body: raw_body,
        rack_test: env["rack.test"]
      }

      case req.path_info
      when "/set-cookie"
        [
          200,
          {
            "content-type" => "application/json",
            "set-cookie" => "session_user=alice; path=/; HttpOnly"
          },
          [JSON.generate({ status: "cookie_set" })]
        ]
      else
        [
          200,
          { "content-type" => "application/json" },
          [JSON.generate(@last_recorded)]
        ]
      end
    end
  end
end
test/contract.rb
# frozen_string_literal: true

require "minitest/autorun"
require "rack"
require "rack/test"
require "json"
require_relative "../src/app"

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

  attr_reader :app_instance

  def app
    @app_instance ||= RackTestV2Contract::RecordingApp.new
  end

  def setup
    @app_instance = RackTestV2Contract::RecordingApp.new
  end

  # 1. Rack::Test v2 removes METHODS constant, removes rack/mock_session require,
  #    and unifies Rack::MockSession as an alias for Rack::Test::Session.
  def test_mock_session_module_exports_and_methods_constant_removal
    # In Rack::Test 1.x, Rack::Test::Methods::METHODS was defined as an Array of symbols.
    # In Rack::Test 2.x, METHODS is no longer defined and raises NameError.
    assert_raises(NameError) do
      Rack::Test::Methods::METHODS
    end

    # In Rack::Test 1.x, Rack::MockSession lived in rack/mock_session.
    # In Rack::Test 2.1+, requiring rack/mock_session raises LoadError.
    assert_raises(LoadError) do
      require "rack/mock_session"
    end

    # In Rack::Test 2.x, Rack::MockSession is an exact alias for Rack::Test::Session.
    assert_equal Rack::Test::Session, Rack::MockSession

    # Instantiating Rack::MockSession returns a Rack::Test::Session instance.
    session = Rack::MockSession.new(app)
    assert_instance_of Rack::Test::Session, session
  end

  # 2. Support :query_params in env to separate URI query string from body payload.
  def test_query_params_env_key_separates_query_string_from_body_payload
    # In Rack::Test 2.x, passing :query_params in the request env appends to the
    # URI query string without contaminating the POST/PUT request body payload.
    post(
      "/submit",
      { "form_field" => "form_value" },
      { :query_params => { "page" => "2", "filter" => "active" } }
    )

    recorded = app_instance.last_recorded
    assert_equal "page=2&filter=active", recorded[:query_string]
    assert_equal({ "page" => "2", "filter" => "active" }, recorded[:get_params])
    assert_equal({ "form_field" => "form_value" }, recorded[:post_params])
    assert_equal(
      { "form_field" => "form_value", "page" => "2", "filter" => "active" },
      recorded[:params]
    )
    assert_equal "form_field=form_value", recorded[:body]

    # :query_params also supports raw query strings
    post(
      "/submit",
      { "action" => "update" },
      { :query_params => "sort=desc&limit=10" }
    )

    recorded2 = app_instance.last_recorded
    assert_equal "sort=desc&limit=10", recorded2[:query_string]
    assert_equal({ "sort" => "desc", "limit" => "10" }, recorded2[:get_params])
    assert_equal({ "action" => "update" }, recorded2[:post_params])
  end

  # 3. Force multipart encoding without file uploads via :multipart or CONTENT_TYPE.
  def test_forced_multipart_via_multipart_env_flag_and_content_type
    # In Rack::Test 1.x, multipart body formatting was only triggered by UploadedFile.
    # In Rack::Test 2.x, passing :multipart => true in env forces multipart/form-data
    # boundary encoding even for regular scalar/Hash parameters.
    post(
      "/submit",
      { "title" => "Test Report", "status" => "draft" },
      { :multipart => true }
    )

    recorded = app_instance.last_recorded
    assert_match(%r{\Amultipart/form-data; boundary=}, recorded[:content_type])
    assert_includes recorded[:body], "content-disposition: form-data; name=\"title\""
    assert_includes recorded[:body], "Test Report"
    assert_includes recorded[:body], "content-disposition: form-data; name=\"status\""
    assert_includes recorded[:body], "draft"
    assert_equal({ "title" => "Test Report", "status" => "draft" }, recorded[:post_params])

    # Specifying CONTENT_TYPE starting with multipart/ also automatically triggers multipart formatting
    header "Content-Type", "multipart/form-data"
    post "/submit", { "category" => "general" }

    recorded_ct = app_instance.last_recorded
    assert_match(%r{\Amultipart/form-data; boundary=}, recorded_ct[:content_type])
    assert_includes recorded_ct[:body], "content-disposition: form-data; name=\"category\""
    assert_includes recorded_ct[:body], "general"
    header "Content-Type", nil
  end

  # 4. default_host method hook in Rack::Test::Methods customizes host resolution.
  def test_default_host_method_hook_customizes_unqualified_uri_routing
    # A testing class can define default_host to redirect relative paths
    # from the default "example.org" to a custom host.
    custom_host_context = Class.new do
      include Rack::Test::Methods

      attr_reader :app

      def initialize(app)
        @app = app
      end

      def default_host
        "api.example.com"
      end
    end.new(app)

    custom_host_context.get "/inspect"
    assert_equal "api.example.com", custom_host_context.last_request.host
    assert_equal "http://api.example.com/inspect", custom_host_context.last_request.url

    # The standard context without default_host continues to default to example.org
    get "/inspect"
    assert_equal "example.org", last_request.host
    assert_equal "http://example.org/inspect", last_request.url
  end

  # 5. restore_state block executes and restores session state (request, response, cookies).
  def test_session_restore_state_isolates_and_reverts_state_mutations
    get "/set-cookie"
    assert_equal "alice", current_session.cookie_jar["session_user"]
    assert_equal "/set-cookie", last_request.path_info
    assert_equal 200, last_response.status

    # Inside restore_state, requests and cookie modifications occur normally:
    current_session.restore_state do
      get "/inspect"
      set_cookie "temporary_flag=1; domain=example.org; path=/"
      assert_equal "/inspect", last_request.path_info
      assert_equal "1", current_session.cookie_jar["temporary_flag"]
      assert_equal "alice", current_session.cookie_jar["session_user"]
    end

    # Upon exiting restore_state, previous request, response, and cookie jar are restored:
    assert_equal "/set-cookie", last_request.path_info
    assert_equal "alice", current_session.cookie_jar["session_user"]
    assert_nil current_session.cookie_jar["temporary_flag"]
  end

  # 6. Rack::Test::Utils internal helper methods are private in v2.
  def test_utils_helper_methods_are_private_in_v2
    # Public methods on Rack::Test::Utils
    assert_respond_to Rack::Test::Utils, :build_nested_query
    assert_respond_to Rack::Test::Utils, :build_multipart

    # Internal formatting helpers made private in 2.0.0 raise NoMethodError if called publicly
    assert_raises(NoMethodError) do
      Rack::Test::Utils.build_primitive_part(String.new, "key", "val")
    end

    assert_raises(NoMethodError) do
      Rack::Test::Utils.build_file_part(String.new, "key", nil)
    end
  end
end

Seeder de origem

csx-seed