forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathformat_test.go
104 lines (89 loc) · 2.04 KB
/
format_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package util
import (
"math"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTruish(t *testing.T) {
cases := []struct {
k string
v bool
}{
{"", false},
{"false", false},
{"0", false},
{"off", false},
{"true", true},
{"1", true},
{"on", true},
}
for _, c := range cases {
assert.Equal(t, c.v, Truish(c.k))
}
}
func TestReplace(t *testing.T) {
cases := []struct {
k string
v interface{}
fmt, expected string
}{
// regex tests
{"foo", true, "${foo}", "true"},
{"foo", true, "${Foo}", "true"},
{"Foo", true, "${foo}", "true"},
{"foo", "1", "abc${foo}${foo}", "abc11"},
{"foo", math.Pi, "${foo:%.2f}", "3.14"},
{"foo", math.Pi, "${foo:%.0f}%", "3%"},
{"foo", 3, "${foo}%", "3%"},
}
for _, c := range cases {
s, err := ReplaceFormatted(c.fmt, map[string]interface{}{
c.k: c.v,
})
require.NoError(t, err)
assert.Equal(t, c.expected, s)
}
}
func TestReplaceMulti(t *testing.T) {
s, err := ReplaceFormatted("${foo}-${bar}", map[string]interface{}{
"foo": "bar",
"bar": "baz",
})
if s != "bar-baz" || err != nil {
t.Error(s, err)
}
}
func TestReplaceNoMatch(t *testing.T) {
s, err := ReplaceFormatted("${foo}", map[string]interface{}{
"bar": "baz",
})
if err == nil {
t.Error(s, err)
}
}
func TestReplaceTemplate(t *testing.T) {
tc := []struct {
in, out, key string
val any
}{
{`"{{ .mode }}"`, `"pv"`, "mode", "pv"},
{`{{ printf "%.1f" .chargedEnergy }}kW`, `1.2kW`, "chargedEnergy", 1.234},
{`{{ round .chargedEnergy 1 }}kW`, `1.2kW`, "chargedEnergy", 1.234},
{`{{ timeRound .connectedDuration "s" }}`, `1s`, "connectedDuration", 1234 * time.Millisecond},
{`{{ timeRound .connectedDuration "m" }}`, `21m0s`, "connectedDuration", 1234 * time.Second},
}
for _, tc := range tc {
s, err := ReplaceFormatted(tc.in, map[string]interface{}{
tc.key: tc.val,
})
t.Log(s)
if err != nil {
t.Error(s, err)
}
if s != tc.out {
t.Errorf("expected: %s, got: %s", tc.out, s)
}
}
}