aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorpukkamustard <pukkamustard@posteo.net>2020-11-17 18:12:19 +0100
committerpukkamustard <pukkamustard@posteo.net>2020-11-17 18:12:19 +0100
commitd8f2484b77dbc4c876e331ab5238dd802bb507c3 (patch)
tree4a5812ee06554c8ee10e0d2f53e3358535ceafeb
parent0bb44269c8e84d0857a2a3c3aae103a3b3a683d5 (diff)
ERIS.ReadCapability: graceful error handling while parsing
-rw-r--r--lib/eris/read_capability.ex14
-rw-r--r--test/eris/read_capability_test.exs46
2 files changed, 57 insertions, 3 deletions
diff --git a/lib/eris/read_capability.ex b/lib/eris/read_capability.ex
index ae9a3fc..e6ea9d6 100644
--- a/lib/eris/read_capability.ex
+++ b/lib/eris/read_capability.ex
@@ -36,11 +36,14 @@ defmodule ERIS.ReadCapability do
|> Base.encode32(padding: false))
end
- def parse(urn) do
+ @doc """
+ Parse an ERIS read capability from a URN (string representaiton) or binary encoding.
+ """
+ def parse(urn) when is_binary(urn) do
case urn do
"urn:erisx2:" <> base32_encoded ->
base32_encoded
- |> Base.decode32!(padding: false)
+ |> Base.decode32(padding: false)
|> parse
<<0>> <> <<level>> <> <<reference::binary-size(32)>> <> <<key::binary-size(32)>> ->
@@ -50,7 +53,12 @@ defmodule ERIS.ReadCapability do
{:ok, %__MODULE__{block_size: 32768, level: level, reference: reference, key: key}}
_ ->
- {:error, "invalid ERIS URN"}
+ {:error, :invalid_read_capability}
end
end
+
+ # handle return from `Base.decode32`
+ def parse({:ok, urn}), do: parse(urn)
+
+ def parse(_), do: {:error, :invalid_read_capability}
end
diff --git a/test/eris/read_capability_test.exs b/test/eris/read_capability_test.exs
new file mode 100644
index 0000000..9d79a52
--- /dev/null
+++ b/test/eris/read_capability_test.exs
@@ -0,0 +1,46 @@
+defmodule ERIS.ReadCapabilityTest do
+ use ExUnit.Case
+
+ alias ERIS.ReadCapability
+
+ doctest ERIS.ReadCapability
+
+ setup do
+ {:ok,
+ %{read_capability: ERIS.encode_read_capability("Hi, I'm testing stuff. Don't mind me.")}}
+ end
+
+ describe "parse/1" do
+ test "can parse valid string urn", %{read_capability: read_capability} do
+ assert {:ok, %ReadCapability{}} =
+ read_capability
+ |> ReadCapability.to_string()
+ |> ReadCapability.parse()
+ end
+
+ test "can parse valid binary read capability", %{read_capability: read_capability} do
+ assert {:ok, %ReadCapability{}} =
+ read_capability
+ |> ReadCapability.to_binary()
+ |> ReadCapability.parse()
+ end
+
+ test "returns error on invalid binary read capability" do
+ assert {:error, :invalid_read_capability} =
+ <<1, 2, 3, 4, 5>>
+ |> ReadCapability.parse()
+ end
+
+ test "returns error on invalid string read capability" do
+ assert {:error, :invalid_read_capability} =
+ "I surely am not a valid URN"
+ |> ReadCapability.parse()
+ end
+
+ test "returns error on invalid Base32 encoding" do
+ assert {:error, :invalid_read_capability} =
+ "urn:erisx2:blups"
+ |> ReadCapability.parse()
+ end
+ end
+end