CodeSampleX

Beispiel

rack-test 2.2.0: Isolate multi-user test sessions with with_session, roll back temporary state with restore_state, and separate POST query parameters from body payloads

Verifiziertes Beispiel für gem rack-test 2.2.0: Isolate multi-user test sessions with with_session, roll back temporary state with restore_state, and…

sha256:9e7a2df8a14d57c31927072a61654e5c2d431dcb37a1990c79781436818f112e

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
2
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung ruby linux x64 ruby ruby rubygems

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
Isolate multi-user test sessions with with_session, roll back temporary state with restore_state, and separate POST query parameters from body payloads
Pakete
Symbole
  • Rack::Test::Methods#with_session
  • Rack::Test::Methods#current_session
  • Rack::Test::Session#restore_state
  • Rack::Test::Session#after_request
  • Rack::Test::Session#env_for
Umgebung
ruby
Erstellt
2026-08-16T16:42:48Z

Contract

  1. assert with_session switches the active session context with isolated cookies and headers, restoring the prior session upon block exit
  2. assert re-entering a named session preserves its prior cookies and session headers
  3. assert restore_state executes nested requests while rolling back last_request, last_response, and cookie jar upon completion
  4. assert post with query_params in env splits URL query parameters from the request body and xhr flag sets HTTP_X_REQUESTED_WITH
  5. assert after_request callbacks execute after every processed request in the session

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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 rack-test Contract

## What search_known_solution answered
`search_known_solution` for `pkg:gem/rack-test` returned three existing samples:
- `sha256:cb16ec9117c9887155c2792e1e4607e740fe8c584754b3d6136855be6762490b`: Sinatra 4 modular app routing and parameter handling.
- `sha256:e873d35fe6c381482a9e0eccc77adc87a49c7dd3a71b3a34b647cabceb3360a5`: Cookie mixed-case path attribute normalization.
- `sha256:b6e08189aff9762145b13c9da3005e5280f936fd2c9e33822f7436a47fdc8cea`: Per-request CGI environment keys, session header persistence, JSON string form-encoding, UploadedFile keyword arguments, and redirect method preservation.

This sample focuses on multi-session isolation via `Rack::Test::Methods#with_session`, temporary state rollback using `Rack::Test::Session#restore_state`, query parameter separation in non-GET requests via `query_params:` and `:xhr`, and `after_request` lifecycle callbacks.

## How the wrong version fails
- **Loud failure**: Attempting to manage multiple users by instantiating manual `Rack::Test::Session.new` instances outside `Rack::Test::Methods` breaks top-level test runner delegators, causing calls to `last_response`, `last_request`, or `header` in shared test helpers to raise `Rack::Test::Error: No response yet` or `NoMethodError`.
- **Silent failure with green build**: Executing multi-user flows in a single default session without `with_session` silently leaks authentication cookies and persistent session headers between test actors, causing downstream authorization tests to falsely pass when requests should have been unauthenticated.
csx.json
{"case":{"believed":"Rack::Test::Methods operates exclusively on a single shared session state, so testing multi-user interactions requires manually creating unmanaged Session instances to avoid leaking cookies and headers.","caseId":"case:sha256:3faf03fc45888fec0541e4841adee53cc93ddb745a844f6a2f7b899ebf7051dd","contract":["assert with_session switches the active session context with isolated cookies and headers, restoring the prior session upon block exit","assert re-entering a named session preserves its prior cookies and session headers","assert restore_state executes nested requests while rolling back last_request, last_response, and cookie jar upon completion","assert post with query_params in env splits URL query parameters from the request body and xhr flag sets HTTP_X_REQUESTED_WITH","assert after_request callbacks execute after every processed request in the session"],"goal":"Isolate multi-user test sessions with with_session, roll back temporary state with restore_state, and separate POST query parameters from body payloads","kind":"HOW","packages":["pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7"],"schemaVersion":1,"symbols":["Rack::Test::Methods#with_session","Rack::Test::Methods#current_session","Rack::Test::Session#restore_state","Rack::Test::Session#after_request","Rack::Test::Session#env_for"]},"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::Methods#with_session","Rack::Test::Methods#current_session","Rack::Test::Session#restore_state","Rack::Test::Session#after_request","Rack::Test::Session#env_for"],"verifierAdapter":"rubygems@1"}
src/app.rb
# frozen_string_literal: true

require "rack"
require "json"

module RackTestMultiSessionContract
  class MultiSessionApp
    def call(env)
      req = Rack::Request.new(env)

      case req.path_info
      when "/login"
        user = req.params["user"] || "anonymous"
        role = req.params["role"] || "guest"
        [
          200,
          {
            "content-type" => "application/json",
            "set-cookie" => "session_user=#{user}; path=/"
          },
          [JSON.generate({ logged_in: user, role: role })]
        ]
      when "/profile"
        user = req.cookies["session_user"] || "nobody"
        auth_header = env["HTTP_X_API_TOKEN"]
        [
          200,
          { "content-type" => "application/json" },
          [JSON.generate({
            user: user,
            token: auth_header,
            xhr: env["HTTP_X_REQUESTED_WITH"],
            query_string: env["QUERY_STRING"],
            method: req.request_method,
            body_params: req.POST,
            query_params: req.GET
          })]
        ]
      when "/audit"
        [
          200,
          {
            "content-type" => "text/plain",
            "set-cookie" => "audit_probe=active; path=/"
          },
          ["audit-ok"]
        ]
      else
        [404, { "content-type" => "text/plain" }, ["not found"]]
      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 RackTestMultiSessionContractTest < Minitest::Test
  include Rack::Test::Methods

  def app
    @app ||= RackTestMultiSessionContract::MultiSessionApp.new
  end

  # 1. with_session isolates cookies, headers, and request history per named session and restores on exit
  def test_with_session_isolation_and_automatic_restoration
    # Default session is unauthenticated
    get "/profile"
    default_info = JSON.parse(last_response.body)
    assert_equal "nobody", default_info["user"]
    assert_nil default_info["token"]

    # Enter isolated session for alice
    with_session(:alice) do
      header "X-Api-Token", "alice-token-123"
      post "/login", { "user" => "alice", "role" => "admin" }

      assert_equal 200, last_response.status
      assert_equal "alice", current_session.cookie_jar["session_user"]

      get "/profile"
      alice_info = JSON.parse(last_response.body)
      assert_equal "alice", alice_info["user"]
      assert_equal "alice-token-123", alice_info["token"]
    end

    # Outside the block, current_session is automatically restored to :default
    # Alice's cookies and persistent headers do not leak into the default session
    get "/profile"
    restored_default = JSON.parse(last_response.body)
    assert_equal "nobody", restored_default["user"]
    assert_nil restored_default["token"]
    assert_nil current_session.cookie_jar["session_user"]

    # Enter a separate isolated session for bob
    with_session(:bob) do
      post "/login", { "user" => "bob", "role" => "member" }
      assert_equal "bob", current_session.cookie_jar["session_user"]

      get "/profile"
      bob_info = JSON.parse(last_response.body)
      assert_equal "bob", bob_info["user"]
      assert_nil bob_info["token"] # Alice's header does not leak to Bob
    end

    # Re-entering :alice session preserves her cookie jar and session headers
    with_session(:alice) do
      get "/profile"
      alice_resumed = JSON.parse(last_response.body)
      assert_equal "alice", alice_resumed["user"]
      assert_equal "alice-token-123", alice_resumed["token"]
    end
  end

  # 2. restore_state rolls back last_request, last_response, and cookie_jar after temporary probes
  def test_restore_state_rolls_back_temporary_requests_and_cookies
    post "/login", { "user" => "primary_user" }
    assert_equal "primary_user", current_session.cookie_jar["session_user"]
    assert_equal "/login", last_request.path_info
    original_body = last_response.body

    current_session.restore_state do
      # Side probe that performs requests and sets cookies
      get "/audit"
      assert_equal 200, last_response.status
      assert_equal "audit-ok", last_response.body
      assert_equal "/audit", last_request.path_info
      assert_equal "active", current_session.cookie_jar["audit_probe"]
    end

    # State is cleanly restored to the pre-block snapshot
    assert_equal "/login", last_request.path_info
    assert_equal original_body, last_response.body
    assert_nil current_session.cookie_jar["audit_probe"]
    assert_equal "primary_user", current_session.cookie_jar["session_user"]
  end

  # 3. Non-GET requests separate body parameters from query_params and inject xhr headers
  def test_post_with_query_params_and_xhr_option
    post "/profile",
      { "action" => "update", "setting" => "dark_mode" },
      { query_params: { "section" => "ui", "page" => 3 }, xhr: true }

    assert_equal 200, last_response.status
    payload = JSON.parse(last_response.body)

    assert_equal "XMLHttpRequest", payload["xhr"]
    assert_equal "section=ui&page=3", payload["query_string"]
    assert_equal({ "action" => "update", "setting" => "dark_mode" }, payload["body_params"])
    assert_equal({ "section" => "ui", "page" => "3" }, payload["query_params"])
  end

  # 4. after_request lifecycle hooks trigger after each request
  def test_after_request_lifecycle_callbacks
    recorded_paths = []
    current_session.after_request do
      recorded_paths << last_request.path_info
    end

    get "/profile"
    post "/login", { "user" => "charlie" }

    assert_equal ["/profile", "/login"], recorded_paths
  end
end

Ursprungs-Seeder

csx-seed