-
Notifications
You must be signed in to change notification settings - Fork 4
/
readme_test.go
65 lines (55 loc) · 1.57 KB
/
readme_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
package exit
import (
_ "embed"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"regexp"
"testing"
)
//go:embed README.md
var readme string
//go:embed exit.go
var src string
func TestExitCodesMatchReadme(t *testing.T) {
var f *ast.File
var err error
re := regexp.MustCompile("\\| (\\d+) \\| `(\\w+)` \\| .* \\|\n")
expectedConstants := make(map[string]string)
for _, submatch := range re.FindAllStringSubmatch(readme, -1) {
expectedConstants[submatch[2]] = submatch[1]
}
fset := token.NewFileSet()
if f, err = parser.ParseFile(fset, "", src, 0); err != nil {
t.Error(err)
}
// Type-check the package.
// We create an empty map for each kind of input
// we're interested in, and Check populates them.
info := types.Info{Defs: make(map[*ast.Ident]types.Object)}
conf := types.Config{Importer: importer.Default()}
if _, err = conf.Check("", fset, []*ast.File{f}, &info); err != nil {
t.Error(err)
}
actualConstants := make(map[string]string)
for id, obj := range info.Defs {
if c, ok := obj.(*types.Const); ok {
actualConstants[id.Name] = c.Val().String()
}
}
// Assertions
for name, expectedValue := range expectedConstants {
if value, ok := actualConstants[name]; !ok {
t.Errorf("exit.go does not define the exit code %q (%s)", name, expectedValue)
} else if value != expectedValue {
t.Errorf("exit.go maps %q to %s, README.md expects it to be %s", name, value, expectedValue)
}
}
for name := range actualConstants {
if _, ok := expectedConstants[name]; !ok {
t.Errorf("exit.go defines an undocumented exit code, %q", name)
}
}
}