Skip to content

Commit

Permalink
Respect minLength when generating string examples (#608)
Browse files Browse the repository at this point in the history
  • Loading branch information
zorbash authored May 23, 2024
1 parent 826ce1d commit 10042c2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
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

0 comments on commit 10042c2

Please sign in to comment.