Debian Codegraph @

strconv/decimal_test.go

raw
1 package strconv
2
3 import (
4 "fmt"
5 "testing"
6
7 "github.com/tdewolff/test"
8 )
9
10 func TestParseDecimal(t *testing.T) {
11 tests := []struct {
12 f string
13 expected float64
14 }{
15 {"5", 5.0},
16 {"5.1", 5.1},
17 {"0.0000000000000000000000000005", 5e-28},
18 {"18446744073709551620", 18446744073709551620.0},
19 {"1000000000000000000000000.0000", 1e24}, // TODO
20 {"1000000000000000000000000000000000000000000", 1e42}, // TODO
21 }
22 for _, tt := range tests {
23 t.Run(fmt.Sprint(tt.f), func(t *testing.T) {
24 f, n := ParseDecimal([]byte(tt.f))
25 test.T(t, n, len(tt.f))
26 test.Float(t, f, tt.expected)
27 })
28 }
29 }
30
31 func TestParseDecimalError(t *testing.T) {
32 tests := []struct {
33 f string
34 n int
35 expected float64
36 }{
37 {"+1", 0, 0.0},
38 {"-1", 2, -1.0},
39 {".", 0, 0.0},
40 {"1e1", 1, 1.0},
41 }
42 for _, tt := range tests {
43 t.Run(fmt.Sprint(tt.f), func(t *testing.T) {
44 f, n := ParseDecimal([]byte(tt.f))
45 test.T(t, n, tt.n)
46 test.T(t, f, tt.expected)
47 })
48 }
49 }
50
51 func TestParseDecimalNegativeFastPath(t *testing.T) {
52 // Dividing by an exact power of ten rounds differently from multiplying
53 // by math.Pow10's inexact reciprocal for some values (e.g. 3 * 0.1 != 3 / 10).
54 for _, tt := range []struct {
55 in string
56 want float64
57 }{
58 {"0.3", 0.3},
59 {"0.7", 0.7},
60 } {
61 f, n := ParseDecimal([]byte(tt.in))
62 if n != len(tt.in) || f != tt.want {
63 t.Errorf("%s: got %v (n=%d), want %v", tt.in, f, n, tt.want)
64 }
65 }
66 }
67
68 func TestAppendDecimal(t *testing.T) {
69 tests := []struct {
70 f float64
71 n int
72 expected string
73 }{
74 {0.0, 0, "0"},
75 {1.0, 2, "1"},
76 {-1.0, 2, "-1"},
77 {1.2, 2, "1.2"},
78 {1.23, 2, "1.23"},
79 {1.234, 2, "1.23"},
80 {1.235, 2, "1.24"},
81 {0.1, 2, "0.1"},
82 {0.01, 2, "0.01"},
83 {0.001, 2, "0"},
84 {0.005, 2, "0.01"},
85 {-75.8077501, 6, "-75.80775"},
86 }
87 for _, tt := range tests {
88 t.Run(fmt.Sprint(tt.f), func(t *testing.T) {
89 b := AppendDecimal(nil, tt.f, tt.n)
90 test.T(t, string(b), tt.expected)
91 })
92 }
93 }
94
95 func FuzzParseDecimal(f *testing.F) {
96 f.Add("5")
97 f.Add("5.1")
98 f.Add("18446744073709551620")
99 f.Add("0.0000000000000000000000000005")
100 f.Fuzz(func(t *testing.T, s string) {
101 ParseDecimal([]byte(s))
102 })
103 }