Skip to content
Open
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
13 changes: 10 additions & 3 deletions lib/ex_junk.ex
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,14 @@ defmodule Junk do
junk_for_type(junk_type, merged_opts)
end

defp junk_for_type(:"Elixir.String", %{prefix: nil} = opts), do: random_string(opts)
defp junk_for_type(:"Elixir.String", %{prefix: ""} = opts), do: random_string(opts)
defp junk_for_type(:"Elixir.String", opts) do
string = random_bytes(opts)
|> Base.url_encode64
opts.prefix <> "-" <> string
opts
|> random_string
|> String.replace_prefix("", opts.prefix <> "-")
end

defp junk_for_type(:"Elixir.Integer", opts) do
min = :math.pow(10, opts.size-1) |> trunc
max = :math.pow(10, opts.size)-1 |> trunc
Expand All @@ -49,4 +52,8 @@ defmodule Junk do
defp random_bytes(%{rand_mod: rand_mod, byte_size: b_size}) do
rand_mod.random_bytes.(b_size)
end

defp random_string(opts) do
opts |> random_bytes |> Base.url_encode64
end
end
8 changes: 8 additions & 0 deletions test/ex_junk_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ defmodule JunkTest do
assert String.starts_with?(output, "prefix-")
end

test "String doesn't start with dash if prefix empty" do
output_with_blank_prefix = Junk.junk(String)
output_with_nil_prefix = Junk.junk(String, prefix: nil)

refute String.starts_with?(output_with_blank_prefix, "-")
refute String.starts_with?(output_with_nil_prefix, "-")
end

test "returns unique Integers" do
assert Junk.junk(Integer) |> is_integer == true
assert Junk.junk(Integer) != Junk.junk(Integer)
Expand Down