Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Allow map options in validate/2 when schema is a list #130

Merged
merged 1 commit into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/nimble_options.ex
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ defmodule NimbleOptions do
validate_options_with_schema(options, schema)
end

def validate(options, schema) when is_list(options) and is_list(schema) do
def validate(options, schema) when (is_list(options) or is_map(options)) and is_list(schema) do
validate(options, new!(schema))
end

Expand Down
26 changes: 26 additions & 0 deletions test/nimble_options_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1735,6 +1735,32 @@ defmodule NimbleOptionsTest do
end
end

# No other test is passing in `opts` as a map, so these are just some white box tests for sanity checking
describe "can use a map for validate/2" do
schema = []
opts = %{}
assert NimbleOptions.validate(opts, schema) == {:ok, %{}}

schema = [
name: [type: :string, required: true],
context: [type: :atom, required: false]
]

opts = %{}

assert NimbleOptions.validate(opts, schema) ==
{:error,
%ValidationError{
key: :name,
value: nil,
keys_path: [],
message: "required :name option not found, received options: []"
}}

opts = %{name: "primary 1"}
assert NimbleOptions.validate(opts, schema) == {:ok, %{name: "primary 1"}}
end

describe "validate!/2 (raising version)" do
test "returns the direct options if the options are valid" do
schema = [name: [], context: []]
Expand Down
Loading