diff --git a/lib/cldr/territory.ex b/lib/cldr/territory.ex index 14d74e8..aac0557 100644 --- a/lib/cldr/territory.ex +++ b/lib/cldr/territory.ex @@ -813,6 +813,9 @@ defmodule Cldr.Territory do iex> Cldr.Territory.to_currency_code("cu") {:ok, :CUP} + + iex> Cldr.Territory.to_currency_code(:CQ) + {:error, {Cldr.UnknownCurrencyError, "No currencies for :CQ were found"}} """ @doc since: "1.2.0" @spec to_currency_code(atom() | String.t() | LanguageTag.t(), Keyword.t()) :: {:ok, atom() | String.t() | charlist()} | {:error, {module(), String.t()}} @@ -823,11 +826,11 @@ defmodule Cldr.Territory do {:error, reason} -> {:error, reason} {:ok, [code | _]} -> {:ok, code} + + {:ok, []} -> {:error, {Cldr.UnknownCurrencyError, "No currencies for #{inspect territory_code} were found"}} end end - - @doc """ The same as `to_currency_code/2`, but raises an exception if it fails. @@ -862,7 +865,6 @@ defmodule Cldr.Territory do end end - @doc """ A helper method to get a territory's currency codes. Returns `{:ok, list}` if successful, otherwise `{:error, reason}`. diff --git a/test/territory_test.exs b/test/territory_test.exs index fa50bc6..2a3b96a 100644 --- a/test/territory_test.exs +++ b/test/territory_test.exs @@ -545,4 +545,32 @@ defmodule Cldr.TerritoryTest do Territory.known_territory_subdivisions(:NOPE, TestBackend.Cldr) end end + + describe "to_currency_code/1" do + test "with valid params" do + assert {:ok, :USD} == Territory.to_currency_code(:US) + assert {:ok, "DKK"} == Territory.to_currency_code(:DK, as: :binary) + end + + test "with invalid params" do + assert {:error, {Cldr.UnknownCurrencyError, "No currencies for :CQ were found"}} == Territory.to_currency_code(:CQ) + assert {:error, {Cldr.UnknownTerritoryError, "The territory \"zz\" is unknown"}} == Territory.to_currency_code("zz") + end + end + + describe "to_currency_code!/1" do + test "with valid params" do + assert :GBP == Cldr.Territory.to_currency_code!(:UK) + assert "SEK" == Cldr.Territory.to_currency_code!(:SE, as: :binary) + end + + test "with invalid params" do + assert_raise Cldr.UnknownCurrencyError, "No currencies for :CQ were found", fn -> + Territory.to_currency_code!(:CQ) + end + assert_raise Cldr.UnknownTerritoryError, "The territory \"zzzzz\" is unknown", fn -> + Territory.to_currency_code!("zzzzz") + end + end + end end