digits-2023-10-15/digits-work-sample-go-bree-.../amount_test.go

120 lines
2.1 KiB
Go

package analyzer
import (
"testing"
)
func TestRounded(t *testing.T) {
type args struct {
num Amount
places int
}
tests := []struct {
name string
args args
want Amount
}{
{
name: "zero",
args: args{num: 0.0, places: 2},
want: 0.0,
},
{
name: "negative",
args: args{num: -30.1, places: 2},
want: -30.1,
},
{
name: "long",
args: args{num: 500.123456789, places: 3},
want: 500.123,
},
{
name: "short",
args: args{num: 500.523456789, places: 1},
want: 500.5,
},
{
name: "money",
args: args{num: 3.50, places: 2},
want: 3.50,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.args.num.Rounded(tt.args.places); got != tt.want {
t.Errorf("Rounded() = %v, want %v", got, tt.want)
}
})
}
}
func TestFormatUSD(t *testing.T) {
type args struct {
dollars Amount
}
tests := []struct {
name string
args args
want string
}{
{
name: "zero",
args: args{dollars: 0.0},
want: "$0.00",
},
{
name: "positive",
args: args{dollars: 13.35423},
want: "$13.35",
},
{
name: "negative",
args: args{dollars: -28.44},
want: "-$28.44",
},
{
name: "large",
args: args{dollars: 56000.03},
want: "$56,000.03",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.args.dollars.FormatUSD(); got != tt.want {
t.Errorf("FormatUSD() = %q, want %q", got, tt.want)
}
})
}
}
func TestAmountAbsoluteValue(t *testing.T) {
cases := map[string]struct {
input Amount
want Amount
}{
"zero": {
input: Amount(0.0),
want: Amount(0.0),
},
"positive unchanged": {
input: Amount(1.0),
want: Amount(1.0),
},
"negative unchanged": {
input: Amount(-0.000001),
want: Amount(0.000001),
},
}
for name, td := range cases {
tt := td // go bug through 1.21+ requires allocating a new variable or setting a go env for experimental features as of go 1.20 (1.21?)
t.Run(name, func(t *testing.T) {
got := tt.input.AbsoluteValue()
if got != tt.want {
t.Errorf("got \n\t%v, want\n\t%v", got, tt.want)
}
})
}
}