Skip to content

Commit

Permalink
Fix/newFromFloat-currency-panic (#145)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
hubarthurcoelho and Rhymond authored Apr 12, 2024
1 parent 226240a commit d338884
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
6 changes: 3 additions & 3 deletions money.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
40 changes: 40 additions & 0 deletions money_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"}`
Expand Down

0 comments on commit d338884

Please sign in to comment.