From d338884af85210bac3cecbe87ec1adcb96fd6b6d Mon Sep 17 00:00:00 2001 From: Arthur Coelho <99970472+hubarthurcoelho@users.noreply.github.com> Date: Fri, 12 Apr 2024 03:15:22 -0300 Subject: [PATCH] Fix/newFromFloat-currency-panic (#145) * test(New-and-NewFromFloat): added test suits with unregistered currency * fix(NewFromFloat): no longer panics when given an invalid or unregistered currency * test(New_WithUnregisteredCurrency): used a better test case --------- Co-authored-by: Raymond --- money.go | 6 +++--- money_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/money.go b/money.go index 28fc431..c359f16 100644 --- a/money.go +++ b/money.go @@ -88,9 +88,9 @@ func New(amount int64, code string) *Money { // NewFromFloat creates and returns new instance of Money from a float64. // Always rounding trailing decimals down. -func NewFromFloat(amount float64, currency string) *Money { - currencyDecimals := math.Pow10(GetCurrency(currency).Fraction) - return New(int64(amount*currencyDecimals), currency) +func NewFromFloat(amount float64, code string) *Money { + currencyDecimals := math.Pow10(newCurrency(code).get().Fraction) + return New(int64(amount*currencyDecimals), code) } // Currency returns the currency used by Money. diff --git a/money_test.go b/money_test.go index e336998..d687222 100644 --- a/money_test.go +++ b/money_test.go @@ -27,6 +27,26 @@ func TestNew(t *testing.T) { } } +func TestNew_WithUnregisteredCurrency(t *testing.T) { + const currencyFooCode = "FOO" + const expectedAmount = 100 + const expectedDisplay = "1.00FOO" + + m := New(100, currencyFooCode) + + if m.amount != expectedAmount { + t.Errorf("Expected amount %d got %d", expectedAmount, m.amount) + } + + if m.currency.Code != currencyFooCode { + t.Errorf("Expected currency code %s got %s", currencyFooCode, m.currency.Code) + } + + if m.Display() != expectedDisplay { + t.Errorf("Expected display %s got %s", expectedDisplay, m.Display()) + } +} + func TestCurrency(t *testing.T) { code := "MOCK" decimals := 5 @@ -672,6 +692,26 @@ func TestNewFromFloat(t *testing.T) { } } +func TestNewFromFloat_WithUnregisteredCurrency(t *testing.T) { + const currencyFooCode = "FOO" + const expectedAmount = 1234 + const expectedDisplay = "12.34FOO" + + m := NewFromFloat(12.34, currencyFooCode) + + if m.amount != expectedAmount { + t.Errorf("Expected amount %d got %d", expectedAmount, m.amount) + } + + if m.currency.Code != currencyFooCode { + t.Errorf("Expected currency code %s got %s", currencyFooCode, m.currency.Code) + } + + if m.Display() != expectedDisplay { + t.Errorf("Expected display %s got %s", expectedDisplay, m.Display()) + } +} + func TestDefaultMarshal(t *testing.T) { given := New(12345, IQD) expected := `{"amount":12345,"currency":"IQD"}`