commit 6547c02e0795bf7371385393a0a8442c7c47233a
parent 893c1997213a392bb261d3ee313fade424793eda
Author: srfsh <dev@srf.sh>
Date: Tue, 19 Jul 2022 18:14:41 +0300
vf/validate: add key/2 to validate public keys and addresses
Diffstat:
2 files changed, 47 insertions(+), 0 deletions(-)
diff --git a/src/zenflows/vf/validate.ex b/src/zenflows/vf/validate.ex
@@ -23,6 +23,19 @@ here are rough and can be changed in the future.
alias Ecto.Changeset, as: Chset
+@doc "Checks if the given string field is [16, 2048] bytes long."
+@spec key(Chset.t(), atom()) :: Chset.t()
+def key(cset, field) do
+ Chset.validate_change(cset, field, :valflow, fn
+ _, str when byte_size(str) < 16 ->
+ [{field, "should be at least 16 bytes long"}]
+ _, str when byte_size(str) > 2048 ->
+ [{field, "should be at most 2048 bytes long"}]
+ _, _ ->
+ []
+ end)
+end
+
@doc "Checks if the given string field is [2, 256] bytes long."
@spec name(Chset.t(), atom()) :: Chset.t()
def name(cset, field) do
diff --git a/test/vf/validate.test.exs b/test/vf/validate.test.exs
@@ -21,6 +21,11 @@ use ExUnit.Case, async: true
alias Ecto.Changeset
alias Zenflows.VF.Validate
+@spec key_chgset(map()) :: Changeset.t()
+defp key_chgset(changes) do
+ Changeset.change({%{}, %{key: :string}}, changes)
+end
+
@spec name_chgset(map()) :: Changeset.t()
defp name_chgset(changes) do
Changeset.change({%{}, %{name: :string}}, changes)
@@ -41,6 +46,35 @@ defp class_chgset(changes) do
Changeset.change({%{}, %{list: {:array, :string}}}, changes)
end
+describe "key/2" do
+ test "with too short param" do
+ assert %Changeset{errors: errs} =
+ %{key: String.duplicate("a", 15)}
+ |> key_chgset()
+ |> Validate.key(:key)
+
+ assert {:ok, _} = Keyword.fetch(errs, :key)
+ end
+
+ test "with too long param" do
+ assert %Changeset{errors: errs} =
+ %{key: String.duplicate("a", 2048 + 1)}
+ |> key_chgset()
+ |> Validate.key(:key)
+
+ assert {:ok, _} = Keyword.fetch(errs, :key)
+ end
+
+ test "with the right size param" do
+ assert %Changeset{errors: errs} =
+ %{key: String.duplicate("a", 16)}
+ |> key_chgset()
+ |> Validate.key(:key)
+
+ assert :error = Keyword.fetch(errs, :key)
+ end
+end
+
describe "name/2" do
test "with too short param" do
assert %Changeset{errors: errs} =