|
4 | 4 | "math/big" |
5 | 5 | "testing" |
6 | 6 |
|
| 7 | + "github.com/stretchr/testify/assert" |
| 8 | + |
7 | 9 | "github.com/cosmos/cosmos-sdk/codec" |
8 | 10 | "github.com/stretchr/testify/require" |
9 | 11 | ) |
@@ -228,26 +230,46 @@ func TestTruncate(t *testing.T) { |
228 | 230 | } |
229 | 231 | } |
230 | 232 |
|
231 | | -func TestToLeftPadded(t *testing.T) { |
| 233 | +var cdc = codec.New() |
| 234 | + |
| 235 | +func TestDecMarshalJSON(t *testing.T) { |
| 236 | + decimal := func(i int64) Dec { |
| 237 | + d := NewDec(0) |
| 238 | + d.Int = new(big.Int).SetInt64(i) |
| 239 | + return d |
| 240 | + } |
232 | 241 | tests := []struct { |
233 | | - dec Dec |
234 | | - digits int8 |
235 | | - exp string |
| 242 | + name string |
| 243 | + d Dec |
| 244 | + want string |
| 245 | + wantErr bool // if wantErr = false, will also attempt unmarshaling |
236 | 246 | }{ |
237 | | - {mustNewDecFromStr(t, "33.3"), 8, "00000033"}, |
238 | | - {mustNewDecFromStr(t, "50"), 8, "00000050"}, |
239 | | - {mustNewDecFromStr(t, "333"), 8, "00000333"}, |
240 | | - {mustNewDecFromStr(t, "333"), 12, "000000000333"}, |
241 | | - {mustNewDecFromStr(t, "0.3333"), 8, "00000000"}, |
| 247 | + {"zero", decimal(0), "\"0.0000000000\"", false}, |
| 248 | + {"one", decimal(1), "\"0.0000000001\"", false}, |
| 249 | + {"ten", decimal(10), "\"0.0000000010\"", false}, |
| 250 | + {"12340", decimal(12340), "\"0.0000012340\"", false}, |
| 251 | + {"zeroInt", NewDec(0), "\"0.0000000000\"", false}, |
| 252 | + {"oneInt", NewDec(1), "\"1.0000000000\"", false}, |
| 253 | + {"tenInt", NewDec(10), "\"10.0000000000\"", false}, |
| 254 | + {"12340Int", NewDec(12340), "\"12340.0000000000\"", false}, |
242 | 255 | } |
243 | | - for tcIndex, tc := range tests { |
244 | | - res := tc.dec.ToLeftPadded(tc.digits) |
245 | | - require.Equal(t, tc.exp, res, "incorrect left padding, tc %d", tcIndex) |
| 256 | + for _, tt := range tests { |
| 257 | + t.Run(tt.name, func(t *testing.T) { |
| 258 | + got, err := tt.d.MarshalJSON() |
| 259 | + if (err != nil) != tt.wantErr { |
| 260 | + t.Errorf("Dec.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr) |
| 261 | + return |
| 262 | + } |
| 263 | + if !tt.wantErr { |
| 264 | + assert.Equal(t, tt.want, string(got), "incorrect marshalled value") |
| 265 | + unmarshalledDec := NewDec(0) |
| 266 | + unmarshalledDec.UnmarshalJSON(got) |
| 267 | + assert.Equal(t, tt.d, unmarshalledDec, "incorrect unmarshalled value") |
| 268 | + } |
| 269 | + }) |
246 | 270 | } |
247 | 271 | } |
248 | 272 |
|
249 | | -var cdc = codec.New() |
250 | | - |
251 | 273 | func TestZeroDeserializationJSON(t *testing.T) { |
252 | 274 | d := Dec{new(big.Int)} |
253 | 275 | err := cdc.UnmarshalJSON([]byte(`"0"`), &d) |
|
0 commit comments