-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathiferr_test.go
54 lines (49 loc) · 1.52 KB
/
iferr_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
package main
import (
"bytes"
"strings"
"testing"
)
func iferrStr(in string, pos int, errMsg string) (string, error) {
out := &bytes.Buffer{}
r := strings.NewReader(in)
err := iferr(out, r, pos, errMsg)
if err != nil {
return "", err
}
return out.String(), nil
}
func iferrOK(t *testing.T, fn string, off int, errMsg, exp string) {
const (
fnPre = "package main\nfunc foo() "
fnPost = " {}"
actPre = "if err != nil {\n\treturn "
actPost = "\n}\n"
)
act, err := iferrStr(fnPre+fn, len(fnPre)+1+off, errMsg)
if err != nil {
t.Errorf("iferr() is failed: %s for %q", err, fn)
return
}
if !strings.HasPrefix(act, actPre) || !strings.HasSuffix(act, actPost) {
t.Errorf("iferr() returns with unexpected prefix or suffix: %q", act)
return
}
act = act[len(actPre) : len(act)-len(actPost)]
if act != exp {
t.Errorf("iferr() returns unexpected: actual=%q expect=%q", act, exp)
return
}
}
func TestIferr(t *testing.T) {
iferrOK(t, `(interface{}, error)`, 0, `err`, `nil, err`)
iferrOK(t, `(map[string]struct{}, error)`, 0, `err`, `nil, err`)
iferrOK(t, `(chan bool, error)`, 0, `err`, `nil, err`)
iferrOK(t, `(bool, error)`, 0, `err`, `false, err`)
iferrOK(t, `(foo, error)`, 0, `err`, `foo{}, err`)
iferrOK(t, `(*foo, error)`, 0, `err`, `nil, err`)
iferrOK(t, `(*foo, error)`, 0, `err`, `nil, err`)
iferrOK(t, `(*foo, error)`, 0, `err`, `nil, err`)
iferrOK(t, `(*foo, error)`, 0, `err`, `nil, err`)
iferrOK(t, `(*foo, error)`, 0, `fmt.Errorf("failed to %v", err)`, `nil, fmt.Errorf("failed to %v", err)`)
}