示例
nimble_options 1.1.1: Measure custom validators and composite option types in NimbleOptions 1.1.1
已验证示例 — hex nimble_options 1.1.1: Measure custom validators and composite option types in NimbleOptions 1.1.1. contract 在 elixir 1 · linux alpine/x64 …
sha256:bf574f199498ebc024cf6e9bdea360f62321db0b50dba14496f956334bbf700f
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
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 custom validators and composite option types in NimbleOptions 1.1.1
- 符号
-
- NimbleOptions.validate
- NimbleOptions.validate!
- NimbleOptions.new!
- NimbleOptions.docs
- 环境
- elixir 1
- 创建时间
- 2026-08-17T04:44:18Z
契约
- assert a custom validator uses an MFA 4-tuple, receives the option value first, returns {:ok, transformed} or {:error, message}, and can replace the validated value
- assert an anonymous-function custom type is rejected while a custom MFA returning a boolean raises RuntimeError
- assert {:or, types} accepts either branch, reports both alternative failures, and retains a transformation from a successful custom branch
- assert typed lists validate and transform every element and report a failing zero-based position
- assert :mfa, :mod_arg, positional tuple, and typed map schemas enforce their measured shapes and error locations
- assert docs with nest_level 1 starts its option list with two spaces
文件
- NOTES.md
- csx.json
- lib/custom_options.ex
- mix.exs
- mix.lock
- test/contract_test.exs
- test/test_helper.exs
源代码
# NimbleOptions Custom Validators, Union Types, and Collection Schemas
## Prior Search
The search query returned published sample `sha256:41ea393de638c575f2f87f965ec5c0d67ac71f5700421b440ef9ae4eae3ec768`, which covered basic keyword list validation, unknown and missing keys, and nested keyword lists.
## Covered Traps in this Sample
1. **Custom Validator MFA Shape and Casting**: `NimbleOptions` rejects anonymous functions or captures `{:custom, &fun/1}` at schema compilation time with `ArgumentError`. Custom validators must be 4-tuples `{:custom, mod, fun, args}`, where the validated value is prepended as the first argument (`apply(mod, fun, [value | args])`). Custom validators must return `{:ok, transformed_val}` or `{:error, message_string}`; returning `{:ok, transformed_val}` transforms the option in place.
2. **Invalid Return from Custom Validator**: Returning a boolean (`true`/`false`) or `:ok` atom fails at runtime with a `RuntimeError` rather than being treated as a successful predicate.
3. **Composite Union Types (`{:or, [...]}`)**: Evaluates type branches in order, preserves transformations from the first matching branch, and reports all alternatives in the error message when all branches fail.
4. **Typed Homogeneous Lists (`{:list, type}`)**: Validates each element, reports the 0-indexed position in the error message (`at index N`), and casts every element in place when given a transforming inner type.
5. **MFA vs Mod-Arg Tuples**: `:mfa` demands `{module, function, list}` and rejects integer arity tuples (`{mod, fun, 2}`), while `:mod_arg` requires `{module, term}` and rejects bare module atoms.
6. **Positional Tuples (`{:tuple, [...]}`)**: Checks exact tuple length and validates element types at each position, reporting the index of the failing element.
7. **Typed Maps (`{:map, key_type, value_type}`)**: Validates arbitrary map key-value pairs, formatting the error path with `at key <key>`.
## Failure Mode
Passing an anonymous function `{:custom, &fun/1}` fails loudly at compile time with `ArgumentError`, returning a boolean from a custom validator fails loudly at runtime with `RuntimeError`, while custom casting silently replaces option values with transformed terms in green builds.
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"believed":"A NimbleOptions custom validator can be an anonymous function that returns a boolean and receives its value after any configured arguments.","caseId":"case:sha256:fcf4a6db5ca189dc6cffb931f54d28ee984f4676b585b9a6bf54f3eccdd909f6","contract":["assert a custom validator uses an MFA 4-tuple, receives the option value first, returns {:ok, transformed} or {:error, message}, and can replace the validated value","assert an anonymous-function custom type is rejected while a custom MFA returning a boolean raises RuntimeError","assert {:or, types} accepts either branch, reports both alternative failures, and retains a transformation from a successful custom branch","assert typed lists validate and transform every element and report a failing zero-based position","assert :mfa, :mod_arg, positional tuple, and typed map schemas enforce their measured shapes and error locations","assert docs with nest_level 1 starts its option list with two spaces"],"goal":"Measure custom validators and composite option types 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"]},"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"],"verifierAdapter":"hex@1"}
defmodule CustomOptions do
@moduledoc """
Demonstrates custom validation MFA contracts, type transformations,
composite union types, and structured collection validation in NimbleOptions.
"""
@doc """
Custom validator that parses a string port into an integer, or validates an integer port.
Demonstrates value transformation/casting and argument prepending.
"""
def parse_port(port, min_port) when is_integer(port) and port >= min_port and port <= 65535 do
{:ok, port}
end
def parse_port(port_str, min_port) when is_binary(port_str) do
case Integer.parse(port_str) do
{int, ""} when int >= min_port and int <= 65535 ->
{:ok, int}
_ ->
{:error, "must be a valid port number between #{min_port} and 65535"}
end
end
def parse_port(_other, min_port) do
{:error, "must be an integer or string port >= #{min_port}"}
end
@doc """
Custom validator that returns a boolean instead of {:ok, val} / {:error, msg}.
NimbleOptions rejects this at runtime with a RuntimeError.
"""
def bool_validator(val), do: is_integer(val)
@schema [
port: [
type: {:custom, __MODULE__, :parse_port, [1024]},
default: 8080,
doc: "Port number (integer or numeric string >= 1024)."
],
fallback_host: [
type: {:or, [:string, {:tuple, [:string, :pos_integer]}]},
default: "localhost",
doc: "Host name or host-port tuple."
],
endpoints: [
type: {:list, {:custom, __MODULE__, :parse_port, [1]}},
default: [80, 443],
doc: "List of allowed service ports (integers or strings)."
],
handler: [
type: :mod_arg,
doc: "Handler tuple of shape {module, argument}."
],
on_error: [
type: :mfa,
doc: "Callback tuple of shape {module, function, args_list}."
],
peer: [
type: {:tuple, [:string, :pos_integer]},
doc: "Peer address tuple {host, port}."
],
headers: [
type: {:map, :string, :string},
default: %{},
doc: "HTTP headers map with string keys and string values."
]
]
@compiled NimbleOptions.new!(@schema)
def validate(opts), do: NimbleOptions.validate(opts, @compiled)
def validate!(opts), do: NimbleOptions.validate!(opts, @compiled)
def schema, do: @compiled
def docs(opts \\ []), do: NimbleOptions.docs(@compiled, opts)
end
defmodule CsxNimbleOptions.MixProject do
use Mix.Project
def project do
[
app: :csx_nimble_options,
version: "0.1.0",
elixir: "~> 1.18",
deps: deps()
]
end
def application, do: [extra_applications: []]
defp deps do
[{:nimble_options, "1.1.1"}]
end
end
%{
"nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"},
}
defmodule CustomOptionsTest do
use ExUnit.Case
alias NimbleOptions.ValidationError
test "custom validator must be an MFA 4-tuple, receives value as first arg, and casts in place" do
# 1. Custom validator casts string port to integer
assert {:ok, opts} = CustomOptions.validate(port: "9000")
assert opts[:port] == 9000
# 2. Custom validator accepts integer port
assert {:ok, opts} = CustomOptions.validate(port: 9000)
assert opts[:port] == 9000
# 3. Custom validator rejects out-of-range value with custom error string
assert {:error, %ValidationError{} = error} = CustomOptions.validate(port: 500)
assert Exception.message(error) ==
"invalid value for :port option: must be an integer or string port >= 1024"
assert error.key == :port
assert error.value == 500
# 4. Anonymous functions and captures are rejected at schema compilation time with ArgumentError
assert_raise ArgumentError, ~r/invalid NimbleOptions schema\..*unknown type/s, fn ->
NimbleOptions.new!(port: [type: {:custom, &is_integer/1}])
end
assert_raise ArgumentError, ~r/invalid NimbleOptions schema\..*unknown type/s, fn ->
NimbleOptions.new!(port: [type: {:custom, fn val -> {:ok, val} end}])
end
end
test "returning a boolean or bare :ok from a custom validator raises a RuntimeError" do
schema = [
val: [
type: {:custom, CustomOptions, :bool_validator, []}
]
]
assert_raise RuntimeError, ~r/custom validation function .* must return \{:ok, value\} or \{:error, message\}, got: true/, fn ->
NimbleOptions.validate([val: 123], schema)
end
end
test "{:or, types} tests validators sequentially, combines types in error, and preserves casts" do
# String branch of {:or, [:string, {:tuple, [:string, :pos_integer]}]}
assert {:ok, opts} = CustomOptions.validate(fallback_host: "example.com")
assert opts[:fallback_host] == "example.com"
# Tuple branch
assert {:ok, opts} = CustomOptions.validate(fallback_host: {"example.com", 8080})
assert opts[:fallback_host] == {"example.com", 8080}
# Error combines all branches
assert {:error, error} = CustomOptions.validate(fallback_host: :invalid_atom)
message = Exception.message(error)
assert message =~ "expected :fallback_host option to match at least one given type"
assert message =~ "expected tuple"
assert message =~ "expected string"
# Ordered evaluation with casting: custom validator runs first, succeeds and casts to integer
transform_schema = [
target: [
type: {:or, [{:custom, CustomOptions, :parse_port, [1]}, :string]}
]
]
assert {:ok, opts} = NimbleOptions.validate([target: "3000"], transform_schema)
assert opts[:target] == 3000
# If first branch fails, second branch (:string) succeeds without casting
assert {:ok, opts} = NimbleOptions.validate([target: "not_a_number"], transform_schema)
assert opts[:target] == "not_a_number"
end
test "{:list, inner_type} validates every element, reports 0-based index, and transforms elements" do
# All elements transformed in place
assert {:ok, opts} = CustomOptions.validate(endpoints: ["80", 443, "8080"])
assert opts[:endpoints] == [80, 443, 8080]
# Index of invalid element reported in message
assert {:error, error} = CustomOptions.validate(endpoints: ["80", -1, "8080"])
assert Exception.message(error) ==
"invalid list in :endpoints option: invalid value for list element at position 1: must be an integer or string port >= 1"
assert error.key == :endpoints
assert error.keys_path == []
assert error.value == ["80", -1, "8080"]
# Empty list accepted
assert {:ok, opts} = CustomOptions.validate(endpoints: [])
assert opts[:endpoints] == []
end
test ":mfa requires {module, function, list} while :mod_arg requires {module, term}" do
# :mfa valid
assert {:ok, opts} = CustomOptions.validate(on_error: {String, :upcase, ["boom"]})
assert opts[:on_error] == {String, :upcase, ["boom"]}
# :mfa rejects integer arity
assert {:error, mfa_err} = CustomOptions.validate(on_error: {String, :upcase, 1})
assert Exception.message(mfa_err) ==
"invalid value for :on_error option: expected tuple {mod, fun, args}, got: {String, :upcase, 1}"
# :mod_arg valid
assert {:ok, opts} = CustomOptions.validate(handler: {URI, "https://example.com"})
assert opts[:handler] == {URI, "https://example.com"}
# :mod_arg rejects bare module atom
assert {:error, mod_err} = CustomOptions.validate(handler: URI)
assert Exception.message(mod_err) =~ "invalid value for :handler option"
assert Exception.message(mod_err) =~ "expected tuple"
end
test "{:tuple, types} checks exact tuple size and element types by position" do
# Valid tuple
assert {:ok, opts} = CustomOptions.validate(peer: {"example.com", 8080})
assert opts[:peer] == {"example.com", 8080}
# Bad element at index 1
assert {:error, elem_err} = CustomOptions.validate(peer: {"example.com", -80})
assert Exception.message(elem_err) ==
"invalid tuple in :peer option: invalid value for tuple element at position 1: expected positive integer, got: -80"
# Bad tuple size
assert {:error, size_err} = CustomOptions.validate(peer: {"example.com"})
assert Exception.message(size_err) =~ "invalid value for :peer option"
assert Exception.message(size_err) =~ "expected tuple"
end
test "{:map, key_type, val_type} validates arbitrary map keys and values with bad key path" do
# Valid map
assert {:ok, opts} = CustomOptions.validate(headers: %{"content-type" => "application/json"})
assert opts[:headers] == %{"content-type" => "application/json"}
# Invalid value reported with at key <key>
assert {:error, val_err} = CustomOptions.validate(headers: %{"retries" => 3})
assert Exception.message(val_err) ==
"invalid map in :headers option: invalid value for map key \"retries\": expected string, got: 3"
# Invalid key reported with at key <key>
assert {:error, key_err} = CustomOptions.validate(headers: %{auth: "token"})
assert Exception.message(key_err) ==
"invalid map in :headers option: invalid value for map key: expected string, got: :auth"
end
test "docs/2 with nest_level indents markdown documentation output" do
docs = CustomOptions.docs(nest_level: 1)
assert String.starts_with?(docs, " * `:port`")
end
end
ExUnit.start()