示例
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
已验证示例 — gem rack-test 2.2.0: Isolate multi-user test sessions with with_session, roll back temporary state with restore_state, and separate POST query…
sha256:9e7a2df8a14d57c31927072a61654e5c2d431dcb37a1990c79781436818f112e
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 2
- 构建过它的签名密钥
- 1
声明的环境
ruby linux x64 ruby ruby rubygems
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| 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 |
案例
HOW- 目标
- Isolate multi-user test sessions with with_session, roll back temporary state with restore_state, and separate POST query parameters from body payloads
- 符号
-
- 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
- 环境
- ruby
- 创建时间
- 2026-08-16T16:42:48Z
契约
- 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
文件
- Gemfile
- NOTES.md
- csx.json
- src/app.rb
- test/contract.rb
源代码
source "https://rubygems.org"
gem "rack-test", "2.2.0"
gem "rack", "3.2.7"
gem "minitest", "5.27.0"
# 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.
{"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"}
# 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
# 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