CodeSampleX

Exemple

nimble_options 1.1.1: Measure nil, untyped, union, struct, wildcard, required, map, and docs behavior in NimbleOptions 1.1.1

Échantillon vérifié pour hex nimble_options 1.1.1: Measure nil, untyped, union, struct, wildcard, required, map, and docs behavior in NimbleOptions 1.1.1. Le…

sha256:5de5eee0a598e06d7d653f53ed7253f189bca205daae8d8d6a48838b483626fc

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
2
Environnement déclaré elixir 1 linux x64 elixir 1 elixir mix

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
Measure nil, untyped, union, struct, wildcard, required, map, and docs behavior in NimbleOptions 1.1.1
Paquets
Symboles
  • NimbleOptions.validate
  • NimbleOptions.validate!
  • NimbleOptions.new!
  • NimbleOptions.docs
  • NimbleOptions.ValidationError
Environnement
elixir 1
Créé
2026-08-17T04:44:45Z

Contrat

  1. assert type: nil accepts nil and rejects tested non-nil values while an omitted type accepts arbitrary terms
  2. assert {:or, [:string, nil]} accepts strings and nil and rejects an atom
  3. assert {:struct, URI} accepts a URI struct and rejects a plain map and a Date struct
  4. assert a wildcard key validates dynamic string options alongside named options and leaves an omitted named default absent
  5. assert a missing required option message lists only the caller-supplied keys rather than inserted defaults
  6. assert maps validate against a compiled NimbleOptions schema while a raw keyword schema raises FunctionClauseError
  7. assert docs omit a type label for nil and render the URI struct type label

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

NOTES.md
# NimbleOptions 1.1.1 type and schema shapes

The contract measures only the pinned release. `type: nil` accepts only nil,
while omitting `:type` accepts arbitrary terms. It also exercises nullable
unions, URI struct validation, wildcard keys, required-key error input lists,
map input against a compiled schema, and the rendered nil and struct type names.
csx.json
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"believed":"type: nil leaves a NimbleOptions key untyped, the same as omitting :type.","caseId":"case:sha256:f5dad39d0e636415fafdf0c31ea5c7d5110dc2b832e6265866f57471aafe3d1c","contract":["assert type: nil accepts nil and rejects tested non-nil values while an omitted type accepts arbitrary terms","assert {:or, [:string, nil]} accepts strings and nil and rejects an atom","assert {:struct, URI} accepts a URI struct and rejects a plain map and a Date struct","assert a wildcard key validates dynamic string options alongside named options and leaves an omitted named default absent","assert a missing required option message lists only the caller-supplied keys rather than inserted defaults","assert maps validate against a compiled NimbleOptions schema while a raw keyword schema raises FunctionClauseError","assert docs omit a type label for nil and render the URI struct type label"],"goal":"Measure nil, untyped, union, struct, wildcard, required, map, and docs behavior in NimbleOptions 1.1.1","kind":"HOW","packages":["pkg:hex/nimble_options@1.1.1"],"schemaVersion":1,"symbols":["NimbleOptions.validate","NimbleOptions.validate!","NimbleOptions.new!","NimbleOptions.docs","NimbleOptions.ValidationError"]},"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/nimble_options@1.1.1"],"schemaVersion":1,"symbols":["NimbleOptions.validate","NimbleOptions.validate!","NimbleOptions.new!","NimbleOptions.docs","NimbleOptions.ValidationError"],"verifierAdapter":"hex@1"}
lib/boundary_options.ex
defmodule BoundaryOptions do
  @moduledoc """
  Schema definitions demonstrating NimbleOptions behavior across version boundaries.
  """

  @endpoint_schema [
    disabled_at: [
      type: nil,
      required: false,
      doc: "Explicit nil sentinel."
    ],
    payload: [
      doc: "Untyped payload defaulting to :any."
    ],
    tag: [
      type: {:or, [:string, nil]},
      default: nil,
      doc: "Nullable string tag."
    ],
    uri: [
      type: {:struct, URI},
      required: false,
      doc: "Target service URI."
    ]
  ]

  @compiled NimbleOptions.new!(@endpoint_schema)

  @doc "Validates endpoint options."
  def validate(opts), do: NimbleOptions.validate(opts, @compiled)

  @doc "Validates endpoint options, raising on failure."
  def validate!(opts), do: NimbleOptions.validate!(opts, @compiled)

  @doc "Returns compiled schema."
  def schema, do: @compiled

  @doc "Returns schema docs."
  def docs, do: NimbleOptions.docs(@compiled)
end
mix.exs
defmodule BoundaryOptions.MixProject do
  use Mix.Project

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

  def application do
    [
      extra_applications: []
    ]
  end

  defp deps do
    [
      {:nimble_options, "1.1.1"}
    ]
  end
end
mix.lock
%{
  "nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"},
}
test/contract_test.exs
defmodule BoundaryOptionsTest do
  use ExUnit.Case

  alias NimbleOptions.ValidationError

  @example_url "https://example.com/api"

  test "type: nil rejects non-nil values, enforcing strict nil rather than untyped wildcard" do
    schema = [disabled_at: [type: nil]]

    # Passing nil succeeds
    assert NimbleOptions.validate([disabled_at: nil], schema) == {:ok, [disabled_at: nil]}

    # Omitting the key succeeds because required defaults to false
    assert NimbleOptions.validate([], schema) == {:ok, []}

    # Passing any non-nil value (string, integer, atom) is rejected with ValidationError
    assert {:error, %ValidationError{} = error} =
             NimbleOptions.validate([disabled_at: "2024-01-01"], schema)

    assert Exception.message(error) ==
             "invalid value for :disabled_at option: expected nil, got: \"2024-01-01\""

    assert error.key == :disabled_at
    assert error.value == "2024-01-01"

    assert {:error, int_error} = NimbleOptions.validate([disabled_at: 0], schema)
    assert Exception.message(int_error) == "invalid value for :disabled_at option: expected nil, got: 0"
  end

  test "omitting :type defaults to :any and accepts arbitrary terms without type errors" do
    untyped_schema = [payload: [doc: "Untyped payload"]]

    assert NimbleOptions.validate([payload: "text"], untyped_schema) == {:ok, [payload: "text"]}
    assert NimbleOptions.validate([payload: 12345], untyped_schema) == {:ok, [payload: 12345]}
    assert NimbleOptions.validate([payload: %{nested: :data}], untyped_schema) ==
             {:ok, [payload: %{nested: :data}]}
    assert NimbleOptions.validate([payload: nil], untyped_schema) == {:ok, [payload: nil]}
  end

  test "{:or, [nil, subtype]} accepts both nil and target subtype while rejecting mismatching types" do
    nullable_schema = [
      tag: [type: {:or, [:string, nil]}],
      count: [type: {:or, [nil, :non_neg_integer]}]
    ]

    assert NimbleOptions.validate([tag: "v1.0", count: 5], nullable_schema) ==
             {:ok, [tag: "v1.0", count: 5]}

    assert NimbleOptions.validate([tag: nil, count: nil], nullable_schema) ==
             {:ok, [tag: nil, count: nil]}

    assert {:error, err} = NimbleOptions.validate([tag: :invalid_atom], nullable_schema)
    assert Exception.message(err) =~ "expected :tag option to match at least one given type"
  end

  test "{:struct, StructName} validates struct instances via is_struct/2 but rejects plain maps" do
    struct_schema = [
      uri: [type: {:struct, URI}]
    ]

    valid_uri = URI.parse(@example_url)
    assert NimbleOptions.validate([uri: valid_uri], struct_schema) == {:ok, [uri: valid_uri]}

    # Plain maps with matching keys fail type validation
    assert {:error, map_err} =
             NimbleOptions.validate([uri: %{host: "example.com", path: "/api"}], struct_schema)

    assert Exception.message(map_err) =~ "invalid value for :uri option: expected URI"
    assert Exception.message(map_err) =~ "path: \"/api\""

    assert {:error, date_err} = NimbleOptions.validate([uri: ~D[2024-01-01]], struct_schema)
    assert Exception.message(date_err) ==
             "invalid value for :uri option: expected URI, got: ~D[2024-01-01]"
  end

  test "wildcard :* allows arbitrary dynamic keys to validate alongside fixed options" do
    wildcard_schema = [
      name: [type: :string, required: true],
      retries: [type: :pos_integer, default: 3],
      *: [type: :string]
    ]

    opts = [name: "worker", env: "production", region: "us-east"]
    assert {:ok, validated} = NimbleOptions.validate(opts, wildcard_schema)
    assert validated[:name] == "worker"
    refute Keyword.has_key?(validated, :retries)
    assert validated[:env] == "production"
    assert validated[:region] == "us-east"

    assert {:error, dyn_err} =
             NimbleOptions.validate([name: "worker", extra_count: 100], wildcard_schema)

    assert Exception.message(dyn_err) ==
             "invalid value for :extra_count option: expected string, got: 100"
  end

  test "missing required options report only caller's originally supplied options in received options: []" do
    order_schema = [
      timeout_ms: [type: :pos_integer, default: 5000],
      api_key: [type: :string, required: true]
    ]

    # In 1.1.1, preceding default values are not leaked into received options
    assert {:error, missing_err} = NimbleOptions.validate([], order_schema)
    assert Exception.message(missing_err) == "required :api_key option not found, received options: []"
    assert missing_err.key == :api_key
    assert missing_err.value == nil

    assert {:error, other_err} =
             NimbleOptions.validate([extra: "val"], order_schema ++ [extra: [type: :string]])

    assert Exception.message(other_err) ==
             "required :api_key option not found, received options: [:extra]"
  end

  test "map options validate against compiled %NimbleOptions{} but raise FunctionClauseError on raw schemas" do
    raw_schema = [
      host: [type: :string, default: "example.com"],
      port: [type: :pos_integer, default: 443]
    ]

    compiled = NimbleOptions.new!(raw_schema)

    assert {:ok, res_map} = NimbleOptions.validate(%{port: 8443}, compiled)
    assert res_map == %{host: "example.com", port: 8443}

    assert_raise FunctionClauseError, fn ->
      apply(NimbleOptions, :validate, [%{port: 8443}, raw_schema])
    end
  end

  test "docs/1 renders nil types and struct types accurately" do
    doc_schema = [
      fallback: [type: nil, doc: "Explicit nil sentinel."],
      endpoint: [type: {:struct, URI}, doc: "Target service URI."]
    ]

    docs = NimbleOptions.docs(doc_schema)

    assert docs =~ "* `:fallback` - Explicit nil sentinel."
    assert docs =~ "* `:endpoint` (struct of type `URI`) - Target service URI."
  end
end
test/test_helper.exs
ExUnit.start()

Seeder d'origine

csx-seed