Skip to content

Commit

Permalink
Fix incorrect error for decimal encoding (#95)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbruggem authored Apr 8, 2024
1 parent b2319a7 commit 70c8337
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/avro_ex/encode.ex
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ defmodule AvroEx.Encode do

%struct{} when struct == Decimal ->
if value.exp != -scale do
error("Incompatible decimal: expected scale #{-scale}, got #{value.exp}")
error({:incompatible_decimal, -scale, value.exp})
end

value.coef * value.sign
Expand Down
6 changes: 6 additions & 0 deletions lib/avro_ex/encode_error.ex
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,10 @@ defmodule AvroEx.EncodeError do
message: "Invalid size for #{type}. Size of #{byte_size(binary)} for #{inspect(binary)}"
}
end

def new({:incompatible_decimal, expected_scale, actual_scale}) do
%__MODULE__{
message: "Incompatible decimal: expected scale #{expected_scale}, got #{actual_scale}"
}
end
end
15 changes: 15 additions & 0 deletions test/encode_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,21 @@ defmodule AvroEx.Encode.Test do
assert encoded == File.read!("test/fixtures/decimal.avro")
end

test "decimal encoding error" do
schema = "test/fixtures/decimal.avsc" |> File.read!() |> AvroEx.decode_schema!()

payload = %{
"decimalField1" => Decimal.new("1E-10"),
"decimalField2" => Decimal.new("0"),
"decimalField3" => Decimal.new("0"),
"decimalField4" => Decimal.new("0")
}

assert_raise(AvroEx.EncodeError, "Incompatible decimal: expected scale -15, got -10", fn ->
AvroEx.encode!(schema, payload)
end)
end

test "decimal without using the Decimal library" do
schema = "test/fixtures/decimal.avsc" |> File.read!() |> AvroEx.decode_schema!()

Expand Down

0 comments on commit 70c8337

Please sign in to comment.