CodeSampleX

Ejemplo

req 0.7.2: Compose request URLs, path parameters, query params, and body steps in Req without network side effects

Muestra verificada para hex req 0.7.2: Compose request URLs, path parameters, query params, and body steps in Req without network side effects. El contrato…

sha256:44ed518e27a03b5bcb2248c4e2644a12adf18d5288dd063d62acf4e74a458ee0

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
2
Entorno declarado elixir linux x64 elixir elixir mix

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
Compose request URLs, path parameters, query params, and body steps in Req without network side effects
Paquetes
Símbolos
  • Req.new
  • Req.Request.register_options
  • Req.Request.put_option
  • Req.Request.run_request
  • Req.Steps.put_base_url
  • Req.Steps.encode_body
  • Req.Steps.put_path_params
  • Req.Steps.put_params
Entorno
elixir
Creado
2026-08-17T04:45:26Z

Contrato

  1. assert Req.Steps.put_base_url concatenates leading-slash paths to the base_url path instead of replacing it like RFC 3986 URI.merge
  2. assert put_base_url evaluates dynamic 0-arity base_url functions and ignores base_url entirely when the request URL has an explicit scheme
  3. assert Req.Steps.encode_body automatically changes request method from :get to :post when body, json, or form is set, but preserves explicit methods like :put
  4. assert Req.Steps.put_path_params URI-encodes values in :colon template style, preserves known unmapped placeholders literally, and raises on uninterned placeholders
  5. assert Req.Steps.put_params decodes existing URL query strings and updates matched keys in place via keystore rather than appending duplicate keys
  6. assert Req validates options against registered keys raising ArgumentError on unregistered options, and a request step returning {req, resp} short-circuits the pipeline

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
`search_known_solution` returned a HIT for `pkg:hex/req@0.7.2` (`sha256:1a5be8dc134928a8238887f9504e70f60f67fb5fa956fd3fc577d86784ecfa1d`), covering HTTP stubbing and response content-type decoding with `Req.Test`. This sample proves a different set of public behaviors in Req: path concatenation semantics for `base_url`, automatic method promotion in `encode_body`, path parameter escaping and placeholder retention in `put_path_params`, query parameter keystore merging in `put_params`, and strict option registration requirements.

A naive assumption fails silently at runtime: assuming `base_url: "https://api.example.com/v1"` and `url: "/users"` behaves like standard RFC 3986 `URI.merge` targets `https://api.example.com/users` instead of `https://api.example.com/v1/users`, and assuming `Req.new(json: %{...})` sends an HTTP GET sends an unintended HTTP POST instead.
csx.json
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"believed":"Merging a leading-slash path into a base_url in Req replaces the base path following RFC 3986, and setting a body on a default request sends a GET request.","caseId":"case:sha256:389f2c6aefc8797fd1605d1355679855b434468f968647d5d76217678c008790","contract":["assert Req.Steps.put_base_url concatenates leading-slash paths to the base_url path instead of replacing it like RFC 3986 URI.merge","assert put_base_url evaluates dynamic 0-arity base_url functions and ignores base_url entirely when the request URL has an explicit scheme","assert Req.Steps.encode_body automatically changes request method from :get to :post when body, json, or form is set, but preserves explicit methods like :put","assert Req.Steps.put_path_params URI-encodes values in :colon template style, preserves known unmapped placeholders literally, and raises on uninterned placeholders","assert Req.Steps.put_params decodes existing URL query strings and updates matched keys in place via keystore rather than appending duplicate keys","assert Req validates options against registered keys raising ArgumentError on unregistered options, and a request step returning {req, resp} short-circuits the pipeline"],"goal":"Compose request URLs, path parameters, query params, and body steps in Req without network side effects","kind":"HOW","packages":["pkg:hex/req@0.7.2"],"schemaVersion":1,"symbols":["Req.new","Req.Request.register_options","Req.Request.put_option","Req.Request.run_request","Req.Steps.put_base_url","Req.Steps.encode_body","Req.Steps.put_path_params","Req.Steps.put_params"]},"contractCommand":["mix","test","--no-deps-check"],"environment":{"arch":"x64","ecosystem":"hex","executionContext":"elixir","language":"elixir","os":"linux","packageManager":"mix","runtime":"elixir","schemaVersion":1},"license":"MIT-0","packages":["pkg:hex/req@0.7.2"],"schemaVersion":1,"symbols":["Req.new","Req.Request.register_options","Req.Request.put_option","Req.Request.run_request","Req.Steps.put_base_url","Req.Steps.encode_body","Req.Steps.put_path_params","Req.Steps.put_params"],"verifierAdapter":"hex@1"}
mix.exs
defmodule CsxReqUrlSteps.MixProject do
  use Mix.Project

  def project do
    [
      app: :csx_req_url_steps,
      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_test.exs
defmodule CsxReqUrlStepsTest do
  use ExUnit.Case, async: true

  test "put_base_url concatenates leading-slash paths to base_url instead of replacing them like RFC 3986" do
    # Standard RFC 3986 / URI.merge resolves ("https://example.com/v1", "/users") to "https://example.com/users".
    # Req.Steps.put_base_url instead joins paths segment-wise, preserving the base URL prefix.
    req1 = Req.new(base_url: "https://api.example.com/v1", url: "/users") |> Req.Steps.put_base_url()
    assert req1.url.path == "/v1/users"
    assert URI.to_string(req1.url) == "https://api.example.com/v1/users"

    # Trailing slash on base and relative path without leading slash produce identical joined path
    req2 = Req.new(base_url: "https://api.example.com/v1/", url: "users") |> Req.Steps.put_base_url()
    assert req2.url.path == "/v1/users"
    assert URI.to_string(req2.url) == "https://api.example.com/v1/users"
  end

  test "put_base_url evaluates dynamic 0-arity functions and is skipped when request URL has a scheme" do
    # Dynamic base_url function evaluation
    req_fn =
      Req.new(base_url: fn -> "https://dynamic.example.com/api" end, url: "/status")
      |> Req.Steps.put_base_url()

    assert URI.to_string(req_fn.url) == "https://dynamic.example.com/api/status"

    # When request URL includes a scheme, base_url is completely ignored
    req_override =
      Req.new(base_url: "https://api.example.com/v1", url: "https://other.example.com/health")
      |> Req.Steps.put_base_url()

    assert URI.to_string(req_override.url) == "https://other.example.com/health"
  end

  test "encode_body automatically changes default GET method to POST when payload is set" do
    # A request constructed with Req.new defaults to method :get
    default_req = Req.new()
    assert default_req.method == :get

    # Setting json automatically mutates method from :get to :post and sets headers
    json_req = Req.new(json: %{tag: "elixir"}) |> Req.Steps.encode_body()
    assert json_req.method == :post
    assert IO.iodata_to_binary(json_req.body) == ~s({"tag":"elixir"})
    assert Req.Request.get_header(json_req, "content-type") == ["application/json"]
    assert Req.Request.get_header(json_req, "accept") == ["application/json"]

    # Setting form also promotes method to :post
    form_req = Req.new(form: [query: "req client"]) |> Req.Steps.encode_body()
    assert form_req.method == :post
    assert form_req.body == "query=req+client"
    assert Req.Request.get_header(form_req, "content-type") == ["application/x-www-form-urlencoded"]

    # Explicit non-GET methods (e.g. :put, :delete) are preserved and not changed to :post
    put_req = Req.new(method: :put, json: %{id: 1}) |> Req.Steps.encode_body()
    assert put_req.method == :put
  end

  test "put_path_params URI-encodes parameters, leaves unmapped existing atoms literal, and raises on uninterned placeholders" do
    # Ensure known atom exists in BEAM atom table for the unmapped placeholder
    _known_atom = :omitted_field

    # Colon style replaces params with URI-encoded values (e.g. "/" encoded to "%2F")
    # Existing atom placeholders absent from path_params remain literal in the path string
    req_colon =
      Req.new(
        url: "/repos/:repo_name/items/:item_id/:omitted_field",
        path_params: [repo_name: "org/core", item_id: 101]
      )
      |> Req.Steps.put_path_params()

    assert req_colon.url.path == "/repos/org%2Fcore/items/101/:omitted_field"

    # Curly style replaces {param} syntax and leaves :colon placeholders intact
    _known_curly = :legacy_id

    req_curly =
      Req.new(
        url: "/users/{user_id}/:legacy_id",
        path_params: [user_id: 42, legacy_id: 99],
        path_params_style: :curly
      )
      |> Req.Steps.put_path_params()

    assert req_curly.url.path == "/users/42/:legacy_id"

    # Uninterned placeholder in path template causes String.to_existing_atom to raise ArgumentError
    assert_raise ArgumentError, fn ->
      # Generate dynamic uninterned key name
      uninterned_key = "uninterned_key_" <> Integer.to_string(System.unique_integer([:positive]))

      Req.new(url: "/test/:" <> uninterned_key, path_params: [item_id: 1])
      |> Req.Steps.put_path_params()
    end
  end

  test "put_params decodes existing query strings and updates keys in place rather than duplicating" do
    # Merging query params into an existing query string updates matched keys and appends new keys
    req =
      Req.new(
        url: "https://api.example.com/search?page=1&sort=asc",
        params: [page: 2, filter: "active"]
      )
      |> Req.Steps.put_params()

    decoded = URI.decode_query(req.url.query)
    assert decoded == %{"page" => "2", "sort" => "asc", "filter" => "active"}

    # Verify that "page" appears exactly once in the decoded key-value list
    decoded_list = URI.query_decoder(req.url.query) |> Enum.to_list()
    assert Enum.count(decoded_list, fn {k, _v} -> k == "page" end) == 1
    assert {"page", "2"} in decoded_list
  end

  test "options must be registered before use and custom request steps can short-circuit the pipeline" do
    # Passing an unregistered option raises ArgumentError
    assert_raise ArgumentError, ~r/unknown option :custom_auth_token/, fn ->
      Req.new(custom_auth_token: "secret")
    end

    # Explicitly registered options are accepted
    req =
      Req.new()
      |> Req.Request.register_options([:custom_auth_token])
      |> Req.Request.put_option(:custom_auth_token, "secret")

    assert req.options[:custom_auth_token] == "secret"

    # Returning {req, resp} from a request step short-circuits execution without reaching adapter
    short_circuit_step = fn request ->
      resp = Req.Response.new(status: 200, body: "mocked_response")
      {request, resp}
    end

    pipeline_req =
      Req.new(url: "https://api.example.com/offline")
      |> Req.Request.prepend_request_steps(mock_cache: short_circuit_step)

    {_req, response} = Req.Request.run_request(pipeline_req)
    assert response.status == 200
    assert response.body == "mocked_response"
  end
end
test/test_helper.exs
ExUnit.start()

Seeder de origen

csx-seed