Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Respect minLength when generating string examples #608

Merged
merged 1 commit into from
May 23, 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
15 changes: 15 additions & 0 deletions lib/open_api_spex/schema.ex
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,21 @@ defmodule OpenApiSpex.Schema do
def example(%Schema{type: :string, format: :"date-time"}), do: "2020-04-20T16:20:00Z"
def example(%Schema{type: :string, format: :uuid}), do: "02ef9c5f-29e6-48fc-9ec3-7ed57ed351f6"

def example(%Schema{type: :string, minLength: 1}), do: "a"
def example(%Schema{type: :string, minLength: 2}), do: "ab"
def example(%Schema{type: :string, minLength: 3}), do: "abc"
def example(%Schema{type: :string, minLength: 4}), do: "abcd"
def example(%Schema{type: :string, minLength: 5}), do: "abcde"
def example(%Schema{type: :string, minLength: 6}), do: "abcdef"

def example(%Schema{type: :string, minLength: min_length})
when is_integer(min_length) and min_length > 0,
do:
~c"example"
|> Stream.cycle()
|> Enum.take(min_length)
|> to_string

def example(%Schema{type: :string}), do: ""
def example(%Schema{type: :integer} = s), do: example_for(s, :integer)
def example(%Schema{type: :number} = s), do: example_for(s, :number)
Expand Down
11 changes: 11 additions & 0 deletions test/schema_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,17 @@ defmodule OpenApiSpex.SchemaTest do
assert Schema.example(%Schema{type: :string}) == ""
end

test "defaults to type-appropriate value for :string with a minLength" do
assert Schema.example(%Schema{type: :string, minLength: 1}) == "a"
assert Schema.example(%Schema{type: :string, minLength: 2}) == "ab"
assert Schema.example(%Schema{type: :string, minLength: 3}) == "abc"
assert Schema.example(%Schema{type: :string, minLength: 4}) == "abcd"
assert Schema.example(%Schema{type: :string, minLength: 5}) == "abcde"
assert Schema.example(%Schema{type: :string, minLength: 6}) == "abcdef"
assert Schema.example(%Schema{type: :string, minLength: 7}) == "example"
assert Schema.example(%Schema{type: :string, minLength: 9}) == "exampleex"
end

test "defaults to type-appropriate value for :integer, :number" do
assert Schema.example(%Schema{type: :integer}) === 0
assert Schema.example(%Schema{type: :number}) === 0
Expand Down
Loading