-
Notifications
You must be signed in to change notification settings - Fork 25
/
fmt_test.go
68 lines (61 loc) · 1.76 KB
/
fmt_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
package gothic
import (
"bytes"
"regexp"
"testing"
)
func test_format(t *testing.T, gold, format string, args ...interface{}) {
var buf bytes.Buffer
err := sprintf(&buf, format, args...)
if err != nil {
t.Error(err)
return
}
s := buf.String()
if gold != s {
t.Errorf("%q != %q", gold, s)
}
}
func must_contain(t *testing.T, err error, re string) {
if err == nil {
t.Error("non-nil error expected")
return
}
r := regexp.MustCompile(re)
if !r.MatchString(err.Error()) {
t.Errorf("%q doesn't contain %q", err, re)
}
}
func test_error(t *testing.T, gold, format string, args ...interface{}) {
var buf bytes.Buffer
err := sprintf(&buf, format, args...)
must_contain(t, err, gold)
}
func TestFormat(t *testing.T) {
am := ArgMap{"i": 10, "j": 5}
test_format(t, "simple as is %{oops}", "simple as is %{oops}")
test_format(t, "10 = 5 + 5", "%{} = %{} + %{1}", 10, 5)
test_format(t, "10 5 5", "%{i} %{j} %{j}", am)
test_format(t, "3.14", "%{%.2f}", 3.1415)
test_format(t, "005", "%{j%03d}", am)
test_format(t, `"\[command \$variable\]"`, "%{%q}", "[command $variable]")
test_error(t, "missing enclosing bracket", "%{} %{", 10, 5)
test_error(t, "not-a-number", "%{oops}", 10, 5)
test_error(t, "there is no.+index -100", "%{-100}", 1, 2, 3)
test_error(t, "there is no.+index 100", "%{100}", 1, 2, 3)
test_error(t, "empty format tag", "%{}", am)
test_error(t, `no argument "x "`, "%{i} %{x }", am)
}
func test_quote(t *testing.T, gold, s string) {
var buf bytes.Buffer
quote(&buf, s)
s2 := buf.String()
if gold != s2 {
t.Errorf("%s != %s (%q)", gold, s2, s)
}
}
func TestQuote(t *testing.T) {
test_quote(t, `"\[command \$variable\]"`, "[command $variable]")
test_quote(t, `"\{1 2 3\}"`, "{1 2 3}")
test_quote(t, `"\a\b\f\n\r\t\v\x00"`, "\a\b\f\n\r\t\v\x00")
}