CodeSampleX

サンプル

req 0.7.2: Measure absent, nil, empty-list, and empty-string header handling in Req 0.7.2

検証済みサンプル — hex req 0.7.2: Measure absent, nil, empty-list, and empty-string header handling in Req 0.7.2. elixir 1 · linux alpine/x64 · docker で contract…

sha256:e52f4de61ddb61a20d40120fde5ea4fc51435b5e9ee5588d1f4eeeafe309ba51

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
2
ビルドした署名鍵
2
宣言された環境 elixir 1 linux x64 elixir 1 elixir mix

検証実行環境

環境 コントラクト ステージ 実行日
elixir 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-17
elixir 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-18

ケース

HOW
ゴール
Measure absent, nil, empty-list, and empty-string header handling in Req 0.7.2
パッケージ
シンボル
  • Req.new
  • Req.Request.put_new_header
  • Req.Request.get_header
  • Req.Request.put_header
  • Req.Request.put_headers
  • Req.Fields.get_list
  • Req.Request.run_request
環境
elixir 1
作成日
2026-08-17T04:47:37Z

コントラクト

  1. assert Req.new retains nil and empty-list header keys with empty-list values while get_header returns [] for both those keys and missing keys
  2. assert put_new_header leaves an existing empty-list value unchanged but populates a genuinely missing key
  3. assert put_header and put_headers replace an existing empty-list value
  4. assert an empty string is stored as one empty string value and is not replaced by put_new_header
  5. assert atom header keys hyphenate underscores while string keys preserve underscores as a separate key
  6. assert the offline adapter sees no flattened wire entries for nil and empty-list headers but sees valid and empty-string headers

ファイル

  • NOTES.md
  • csx.json
  • mix.exs
  • mix.lock
  • test/contract.exs
  • test/contract_test.exs
  • test/test_helper.exs

ソースアーティファクトをダウンロード (tar.gz)

ソース

NOTES.md
# Req Header Edge Domain and Normalization

## Known solution search result

`search_known_solution` answered with sample `sha256:44ed518e27a03b5bcb2248c4e2644a12adf18d5288dd063d62acf4e74a458ee0` (Goal: Compose request URLs, path parameters, query params, and body steps in Req without network side effects). That sample explores basic URL composition and path parameter expansion, but does not cover the edge behaviour of `nil`/empty list headers, header default shadowing, or atom-versus-string key normalization.

## Trap details

When initializing or modifying headers in `Req` (e.g. `Req.new(headers: [authorization: nil, x_client_id: []])`):
- `Req.Fields.new/1` normalizes `nil` and `[]` values into an empty list `[]` stored in `req.headers` as `%{"authorization" => [], "x-client-id" => []}`.
- Calling `Req.Request.get_header(req, "authorization")` returns `[]`, which is indistinguishable from a header that was never set.
- Calling `Req.Request.put_new_header(req, "authorization", "Bearer default_token")` relies on `Map.put_new/3` against `req.headers`. Because the key `"authorization"` already exists in the map, `put_new_header` silently no-ops, discarding the default value.
- On the wire, empty list headers emit zero header lines, whereas an empty string header `""` is stored as `[""]` and emits an empty-value header line.
- Atom header keys convert underscores to hyphens (`:x_custom_header` becomes `"x-custom-header"`), while string header keys preserve underscores (`"x_custom_header"`), maintaining two distinct keys in `req.headers`.

## How the wrong version fails

Silently, with a green build: `Req.Request.get_header/2` returns `[]` indicating no header value, yet downstream middleware attempting to apply defaults with `Req.Request.put_new_header/3` will silently fail to insert the default value without any exception being raised.
csx.json
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"believed":"A nil or empty-list Req header is absent from the internal map, so put_new_header supplies a fallback and get_header distinguishes it from a missing header.","caseId":"case:sha256:297cad1b89665d2ef074765429b30db59af52fa1378d9868cb921eac2934bbc4","contract":["assert Req.new retains nil and empty-list header keys with empty-list values while get_header returns [] for both those keys and missing keys","assert put_new_header leaves an existing empty-list value unchanged but populates a genuinely missing key","assert put_header and put_headers replace an existing empty-list value","assert an empty string is stored as one empty string value and is not replaced by put_new_header","assert atom header keys hyphenate underscores while string keys preserve underscores as a separate key","assert the offline adapter sees no flattened wire entries for nil and empty-list headers but sees valid and empty-string headers"],"goal":"Measure absent, nil, empty-list, and empty-string header handling in Req 0.7.2","kind":"HOW","packages":["pkg:hex/req@0.7.2"],"schemaVersion":1,"symbols":["Req.new","Req.Request.put_new_header","Req.Request.get_header","Req.Request.put_header","Req.Request.put_headers","Req.Fields.get_list","Req.Request.run_request"]},"contractCommand":["mix","test","--no-deps-check"],"environment":{"arch":"x64","ecosystem":"hex","executionContext":"elixir","language":"elixir","os":"linux","packageManager":"mix","runtime":"elixir","runtimeVersion":"1","schemaVersion":1},"license":"MIT-0","packages":["pkg:hex/req@0.7.2"],"schemaVersion":1,"symbols":["Req.new","Req.Request.put_new_header","Req.Request.get_header","Req.Request.put_header","Req.Request.put_headers","Req.Fields.get_list","Req.Request.run_request"],"verifierAdapter":"hex@1"}
mix.exs
defmodule ReqHeaderEdge.MixProject do
  use Mix.Project

  def project do
    [
      app: :req_header_edge,
      version: "0.1.0",
      elixir: "~> 1.15",
      deps: deps()
    ]
  end

  def application do
    [
      extra_applications: [:logger]
    ]
  end

  defp deps do
    [
      {:req, "0.7.2"}
    ]
  end
end
mix.lock
%{
  "finch": {:hex, :finch, "0.23.0", "e3f9287ac25a8832f848b144c2b57346aac65b205e2e0629a52adfe6507fd837", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "80e58d3f936f57e3fdf404f83a3642897ae6d9fb642934e46da4d8fe761b99d5"},
  "hpax": {:hex, :hpax, "1.0.4", "777de5d433b0fbdc7c418159c8055910faa8047ffdb3d6b31098d2a46cd7685c", [:mix], [], "hexpm", "afc7cb142ebcc2d01ce7816190b98ce5dd49e799111b24249f3443d730f377ca"},
  "jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"},
  "mime": {:hex, :mime, "2.0.7", "b8d739037be7cd402aee1ba0306edfdef982687ee7e9859bee6198c1e7e2f128", [:mix], [], "hexpm", "6171188e399ee16023ffc5b76ce445eb6d9672e2e241d2df6050f3c771e80ccd"},
  "mint": {:hex, :mint, "1.9.3", "3337184d69179695c7a9f1714d92c11e629d36c8c037a21cf490131d3d150554", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 0.1.1 or ~> 0.2.0 or ~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "5f7c9342480c069dbbc4eeac3490303c9e01870ff01a7f1d29b6107054fc1e74"},
  "nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"},
  "nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"},
  "req": {:hex, :req, "0.7.2", "364eae2e5f5c984f2dac6d71c07f8c8c89ce0bc49c4d746dacb7a306823020de", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "c9cdfa276b05d8db2a27fda5d233e6858b764d47189d76cbb186e130a871ae0b"},
  "telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
}
test/contract.exs
defmodule HeaderEdgeDomainContractTest do
  use ExUnit.Case, async: true

  test "Req stores nil and [] header values as empty lists, causing put_new_header to skip setting defaults" do
    req = Req.new(headers: [authorization: nil, x_client_id: []])

    # The keys exist in the headers map, but map to empty lists
    assert req.headers == %{"authorization" => [], "x-client-id" => []}

    # Req.Request.get_header returns [] for explicit nil/[] headers
    assert Req.Request.get_header(req, "authorization") == []
    assert Req.Request.get_header(req, "x-client-id") == []

    # Req.Request.get_header also returns [] for completely unset/missing headers
    assert Req.Request.get_header(req, "non-existent-header") == []

    # Attempting to set a default with put_new_header silently no-ops because the key already exists in map
    req_after_default = Req.Request.put_new_header(req, "authorization", "Bearer default_token")
    assert Req.Request.get_header(req_after_default, "authorization") == []
    assert req_after_default.headers["authorization"] == []

    # In contrast, an unset header is successfully populated by put_new_header
    req_with_new = Req.Request.put_new_header(req, "non-existent-header", "default_val")
    assert Req.Request.get_header(req_with_new, "non-existent-header") == ["default_val"]
  end

  test "put_header and put_headers overwrite existing empty list headers" do
    req = Req.new(headers: [authorization: nil])
    assert req.headers["authorization"] == []

    # put_header replaces the value list unconditionally
    req_updated = Req.Request.put_header(req, "authorization", "Bearer active_token")
    assert Req.Request.get_header(req_updated, "authorization") == ["Bearer active_token"]
    assert req_updated.headers["authorization"] == ["Bearer active_token"]

    # put_headers also overrides empty list headers
    req_multi = Req.Request.put_headers(req, [{"authorization", "Bearer multi_token"}])
    assert Req.Request.get_header(req_multi, "authorization") == ["Bearer multi_token"]
  end

  test "empty string header produces a single empty string element rather than empty list" do
    req = Req.new(headers: [x_empty: ""])

    # Empty string is preserved as [""]
    assert req.headers["x-empty"] == [""]
    assert Req.Request.get_header(req, "x-empty") == [""]

    # put_new_header does not overwrite existing [""]
    req_noop = Req.Request.put_new_header(req, "x-empty", "fallback")
    assert Req.Request.get_header(req_noop, "x-empty") == [""]
  end

  test "atom keys hyphenate underscores while string keys preserve underscores" do
    req = Req.new(headers: [{"x_custom_header", "string_val"}, {:x_custom_header, "atom_val"}])

    # Atom key :x_custom_header becomes "x-custom-header"
    assert Req.Request.get_header(req, "x-custom-header") == ["atom_val"]

    # String key "x_custom_header" retains underscore "x_custom_header"
    assert Req.Request.get_header(req, "x_custom_header") == ["string_val"]

    # They reside under distinct map keys
    assert req.headers["x-custom-header"] == ["atom_val"]
    assert req.headers["x_custom_header"] == ["string_val"]
  end

  test "offline adapter execution emits zero wire headers for nil and empty list entries" do
    test_pid = self()

    adapter = fn request ->
      # Wire headers representation using Req.Fields.get_list
      wire_headers = Req.Fields.get_list(request.headers)
      send(test_pid, {:captured_wire_headers, wire_headers})

      {request, Req.Response.new(status: 200, body: "ok")}
    end

    req =
      Req.new(
        url: "https://example.com/test",
        headers: [
          authorization: nil,
          x_absent_list: [],
          x_valid: "active",
          x_empty_str: ""
        ],
        adapter: adapter
      )

    {_req, resp} = Req.Request.run_request(req)
    assert resp.status == 200

    assert_receive {:captured_wire_headers, wire_headers}

    header_names = Enum.map(wire_headers, &elem(&1, 0))

    # "authorization" and "x-absent-list" are completely absent from wire headers
    refute "authorization" in header_names
    refute "x-absent-list" in header_names

    # "x-valid" and "x-empty-str" are present
    assert {"x-valid", "active"} in wire_headers
    assert {"x-empty-str", ""} in wire_headers
  end
end
test/contract_test.exs
Code.require_file("contract.exs", __DIR__)
test/test_helper.exs
ExUnit.start()

オリジンシーダー

csx-seed