|
| 1 | +package bigint |
| 2 | + |
| 3 | +import ( |
| 4 | + "math/big" |
| 5 | + "testing" |
| 6 | +) |
| 7 | + |
| 8 | +func TestParse(t *testing.T) { |
| 9 | + cases := []struct { |
| 10 | + name string |
| 11 | + in string |
| 12 | + want string // big.Int decimal string, ignored when wantErr is set |
| 13 | + wantErr string |
| 14 | + }{ |
| 15 | + {name: "zero", in: "0", want: "0"}, |
| 16 | + {name: "decimal", in: "4000000", want: "4000000"}, |
| 17 | + {name: "leading zero is decimal not octal", in: "010", want: "10"}, |
| 18 | + {name: "negative decimal", in: "-5", want: "-5"}, |
| 19 | + {name: "lowercase hex", in: "0x3D0900", want: "4000000"}, |
| 20 | + {name: "uppercase hex prefix", in: "0X3d0900", want: "4000000"}, |
| 21 | + {name: "hex with leading zero digits", in: "0x00ff", want: "255"}, |
| 22 | + {name: "trims whitespace", in: " 42 ", want: "42"}, |
| 23 | + {name: "huge value preserved", in: "100000000000000000000", want: "100000000000000000000"}, |
| 24 | + |
| 25 | + {name: "empty", in: "", wantErr: "expected numeric value, got ''"}, |
| 26 | + {name: "whitespace only", in: " ", wantErr: "expected numeric value, got ''"}, |
| 27 | + {name: "0x with no digits", in: "0x", wantErr: "expected numeric value, got '0x'"}, |
| 28 | + {name: "non-numeric", in: "MAX", wantErr: "expected numeric value, got 'MAX'"}, |
| 29 | + {name: "invalid hex digits", in: "0xZZZ", wantErr: "expected numeric value, got '0xZZZ'"}, |
| 30 | + {name: "decimal with letters", in: "12abc", wantErr: "expected numeric value, got '12abc'"}, |
| 31 | + } |
| 32 | + |
| 33 | + for _, tc := range cases { |
| 34 | + t.Run(tc.name, func(t *testing.T) { |
| 35 | + got, err := Parse(tc.in) |
| 36 | + if tc.wantErr != "" { |
| 37 | + if err == nil { |
| 38 | + t.Fatalf("Parse(%q) = %v, want error %q", tc.in, got, tc.wantErr) |
| 39 | + } |
| 40 | + if err.Error() != tc.wantErr { |
| 41 | + t.Fatalf("Parse(%q) error = %q, want %q", tc.in, err.Error(), tc.wantErr) |
| 42 | + } |
| 43 | + return |
| 44 | + } |
| 45 | + if err != nil { |
| 46 | + t.Fatalf("Parse(%q) unexpected error: %v", tc.in, err) |
| 47 | + } |
| 48 | + want, _ := new(big.Int).SetString(tc.want, 10) |
| 49 | + if got.Cmp(want) != 0 { |
| 50 | + t.Fatalf("Parse(%q) = %s, want %s", tc.in, got.String(), tc.want) |
| 51 | + } |
| 52 | + }) |
| 53 | + } |
| 54 | +} |
0 commit comments