forked from droyo/go-xml
/
testgen.go
204 lines (185 loc) · 4.95 KB
/
testgen.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// testgen is a wrapper around xsdgen that generates unit
// for generated code.
package main
import (
"encoding/xml"
"fmt"
"go/ast"
"io/ioutil"
"log"
"path/filepath"
"strings"
"aqwari.net/xml/internal/gen"
"aqwari.net/xml/xmltree"
"aqwari.net/xml/xsd"
"aqwari.net/xml/xsdgen"
)
func glob(pat string) string {
f, err := filepath.Glob(pat)
if err != nil {
log.Fatal(err)
}
if len(f) < 1 {
log.Fatal("no files match ", pat)
}
return f[0]
}
func main() {
cfg := new(xsdgen.Config)
cases := findTestCases()
cfg.Option(xsdgen.DefaultOptions...)
for _, dir := range cases {
data, err := ioutil.ReadFile(glob(filepath.Join(dir, "*.xsd")))
if err != nil {
log.Print(err)
continue
}
tests, err := genTests(*cfg, data, dir)
if err != nil {
log.Print(dir, ":", err)
continue
} else {
log.Printf("generated tests for %s", dir)
}
filename := filepath.Join(dir, dir+"_test.go")
source, err := gen.FormattedSource(tests, filename)
if err != nil {
log.Print(dir, ":", err)
continue
}
if err := ioutil.WriteFile(filename, source, 0666); err != nil {
log.Print(dir, ":", err)
}
// This is needed so 'go build' works and automated CI doesn't complain.
err = ioutil.WriteFile(filepath.Join(dir, dir+".go"), []byte("package "+dir+"\n"), 0666)
if err != nil {
log.Print(err)
}
}
}
// Generates unit tests for xml marshal unmarshalling of
// schema-generated code. The unit test will do the
// following:
//
// - Unmarshal the sample data (dataFile) into a struct representing
// the document described in the XML schema.
// - Marshal the resulting file back into an XML document.
// - Compare the two documents for equality.
func genTests(cfg xsdgen.Config, data []byte, dir string) (*ast.File, error) {
cfg.Option(xsdgen.PackageName(dir))
code, err := cfg.GenCode(data)
if err != nil {
return nil, err
}
file, err := code.GenAST()
if err != nil {
return nil, err
}
// We look for top-level elements in the schema to determine what
// the example document looks like.
roots, err := xsd.Normalize(data)
if err != nil {
return nil, err
}
if len(roots) < 1 {
return nil, fmt.Errorf("no schema in %s", dir)
}
root := roots[0]
doc := topLevelElements(root)
fields := make([]ast.Expr, 0, len(doc)*3)
for _, elem := range doc {
fields = append(fields,
gen.Public(elem.Name.Local),
ast.NewIdent(code.NameOf(elem.Type)),
gen.String(fmt.Sprintf(`xml:"%s %s"`, elem.Name.Space, elem.Name.Local)))
}
expr, err := gen.ToString(gen.Struct(fields...))
if err != nil {
return nil, err
}
var params struct {
DocStruct string
Dir string
}
params.DocStruct = expr
params.Dir = dir
fn, err := gen.Func("Test"+strings.Title(dir)).
Args("t *testing.T").
BodyTmpl(`
type Document {{.DocStruct}}
var document Document
samples, err := filepath.Glob(filepath.Join("*.xml"))
if err != nil {
t.Fatal(err)
}
if len(samples) != 1 {
t.Fatal("expected one sample file, found ", samples)
}
input, err := ioutil.ReadFile(samples[0])
if err != nil {
t.Fatal(err)
}
input = append([]byte("<Document>\n"), input...)
input = append(input, []byte("</Document>")...)
if err := xml.Unmarshal(input, &document); err != nil {
t.Fatal("unmarshal: ", err)
}
output, err := xml.Marshal(&document)
if err != nil {
t.Fatal("marshal: ", err)
}
inputTree, err := xmltree.Parse(input)
if err != nil {
t.Fatal("{{.Dir}}: ", err)
}
outputTree, err := xmltree.Parse(output)
if err != nil {
t.Fatal("remarshal: ", err)
}
if !xmltree.Equal(inputTree, outputTree) {
t.Errorf("got \n%s\n, wanted \n%s\n",
xmltree.MarshalIndent(outputTree, "", " "),
xmltree.MarshalIndent(inputTree, "", " "))
}
`, params).Decl()
if err != nil {
return nil, err
}
// Test goes at the top
file.Decls = append([]ast.Decl{fn}, file.Decls...)
return file, nil
}
type Element struct {
Name, Type xml.Name
}
func topLevelElements(root *xmltree.Element) []Element {
const schemaNS = "http://www.w3.org/2001/XMLSchema"
result := make([]Element, 0)
root = &xmltree.Element{Scope: root.Scope, Children: []xmltree.Element{*root}}
for _, schema := range root.Search(schemaNS, "schema") {
tns := schema.Attr("", "targetNamespace")
for _, el := range schema.Children {
if (el.Name == xml.Name{schemaNS, "element"}) {
result = append(result, Element{
Name: el.ResolveDefault(el.Attr("", "name"), tns),
Type: el.Resolve(el.Attr("", "type")),
})
}
}
}
return result
}
// Looks for subdirectories containing pairs of (xml, xsd) files
// that should contain an xml document and the schema it conforms to,
// respectively. Returns slice of the directory names
func findTestCases() []string {
filenames, err := filepath.Glob("*/*.xsd")
if err != nil {
return nil
}
result := make([]string, 0, len(filenames))
for _, xsdfile := range filenames {
result = append(result, filepath.Base(filepath.Dir(xsdfile)))
}
return result
}