bson_corpus_spec_test_generator.go 6.3 KB
Newer Older
Z
zhangmin 已提交
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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
// +build ignore

package main

import (
	"bytes"
	"fmt"
	"go/format"
	"html/template"
	"io/ioutil"
	"log"
	"path/filepath"
	"strings"

	"github.com/globalsign/mgo/internal/json"
)

func main() {
	log.SetFlags(0)
	log.SetPrefix(name + ": ")

	var g Generator

	fmt.Fprintf(&g, "// Code generated by \"%s.go\"; DO NOT EDIT\n\n", name)

	src := g.generate()

	err := ioutil.WriteFile(fmt.Sprintf("%s.go", strings.TrimSuffix(name, "_generator")), src, 0644)
	if err != nil {
		log.Fatalf("writing output: %s", err)
	}
}

// Generator holds the state of the analysis. Primarily used to buffer
// the output for format.Source.
type Generator struct {
	bytes.Buffer // Accumulated output.
}

// format returns the gofmt-ed contents of the Generator's buffer.
func (g *Generator) format() []byte {
	src, err := format.Source(g.Bytes())
	if err != nil {
		// Should never happen, but can arise when developing this code.
		// The user can compile the output to see the error.
		log.Printf("warning: internal error: invalid Go generated: %s", err)
		log.Printf("warning: compile the package to analyze the error")
		return g.Bytes()
	}
	return src
}

// EVERYTHING ABOVE IS CONSTANT BETWEEN THE GENERATORS

const name = "bson_corpus_spec_test_generator"

func (g *Generator) generate() []byte {

	testFiles, err := filepath.Glob("./specdata/specifications/source/bson-corpus/tests/*.json")
	if err != nil {
		log.Fatalf("error reading bson-corpus files: %s", err)
	}

	tests, err := g.loadTests(testFiles)
	if err != nil {
		log.Fatalf("error loading tests: %s", err)
	}

	tmpl, err := g.getTemplate()
	if err != nil {
		log.Fatalf("error loading template: %s", err)
	}

	tmpl.Execute(&g.Buffer, tests)

	return g.format()
}

func (g *Generator) loadTests(filenames []string) ([]*testDef, error) {
	var tests []*testDef
	for _, filename := range filenames {
		test, err := g.loadTest(filename)
		if err != nil {
			return nil, err
		}

		tests = append(tests, test)
	}

	return tests, nil
}

func (g *Generator) loadTest(filename string) (*testDef, error) {
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	var testDef testDef
	err = json.Unmarshal(content, &testDef)
	if err != nil {
		return nil, err
	}

	names := make(map[string]struct{})

	for i := len(testDef.Valid) - 1; i >= 0; i-- {
		if testDef.BsonType == "0x05" && testDef.Valid[i].Description == "subtype 0x02" {
			testDef.Valid = append(testDef.Valid[:i], testDef.Valid[i+1:]...)
			continue
		}

		name := cleanupFuncName(testDef.Description + "_" + testDef.Valid[i].Description)
		nameIdx := name
		j := 1
		for {
			if _, ok := names[nameIdx]; !ok {
				break
			}

			nameIdx = fmt.Sprintf("%s_%d", name, j)
		}

		names[nameIdx] = struct{}{}

		testDef.Valid[i].TestDef = &testDef
		testDef.Valid[i].Name = nameIdx
		testDef.Valid[i].StructTest = testDef.TestKey != "" &&
			(testDef.BsonType != "0x05" || strings.Contains(testDef.Valid[i].Description, "0x00")) &&
			!testDef.Deprecated
	}

	for i := len(testDef.DecodeErrors) - 1; i >= 0; i-- {
		if strings.Contains(testDef.DecodeErrors[i].Description, "UTF-8") {
			testDef.DecodeErrors = append(testDef.DecodeErrors[:i], testDef.DecodeErrors[i+1:]...)
			continue
		}

		name := cleanupFuncName(testDef.Description + "_" + testDef.DecodeErrors[i].Description)
		nameIdx := name
		j := 1
		for {
			if _, ok := names[nameIdx]; !ok {
				break
			}

			nameIdx = fmt.Sprintf("%s_%d", name, j)
		}
		names[nameIdx] = struct{}{}

		testDef.DecodeErrors[i].Name = nameIdx
	}

	return &testDef, nil
}

func (g *Generator) getTemplate() (*template.Template, error) {
	content := `package bson_test

import (
    "encoding/hex"
	"time"

	. "gopkg.in/check.v1"
    "github.com/globalsign/mgo/bson"
)

func testValid(c *C, in []byte, expected []byte, result interface{}) {
	err := bson.Unmarshal(in, result)
	c.Assert(err, IsNil)

	out, err := bson.Marshal(result)
	c.Assert(err, IsNil)

	c.Assert(string(expected), Equals, string(out), Commentf("roundtrip failed for %T, expected '%x' but got '%x'", result, expected, out))
}

func testDecodeSkip(c *C, in []byte) {
	err := bson.Unmarshal(in, &struct{}{})
	c.Assert(err, IsNil)
}

func testDecodeError(c *C, in []byte, result interface{}) {
	err := bson.Unmarshal(in, result)
	c.Assert(err, Not(IsNil))
}

{{range .}}
{{range .Valid}}
func (s *S) Test{{.Name}}(c *C) {
    b, err := hex.DecodeString("{{.Bson}}")
	c.Assert(err, IsNil)

    {{if .CanonicalBson}}
    cb, err := hex.DecodeString("{{.CanonicalBson}}")
	c.Assert(err, IsNil)
	{{else}}
    cb := b
    {{end}}

    var resultD bson.D
	testValid(c, b, cb, &resultD)
	{{if .StructTest}}var resultS struct {
		Element {{.TestDef.GoType}} ` + "`bson:\"{{.TestDef.TestKey}}\"`" + `
	}
	testValid(c, b, cb, &resultS){{end}}

	testDecodeSkip(c, b)
}
{{end}}

{{range .DecodeErrors}}
func (s *S) Test{{.Name}}(c *C) {
	b, err := hex.DecodeString("{{.Bson}}")
	c.Assert(err, IsNil)

	var resultD bson.D
	testDecodeError(c, b, &resultD)
}
{{end}}
{{end}}
`
	tmpl, err := template.New("").Parse(content)
	if err != nil {
		return nil, err
	}
	return tmpl, nil
}

func cleanupFuncName(name string) string {
	return strings.Map(func(r rune) rune {
		if (r >= 48 && r <= 57) || (r >= 65 && r <= 90) || (r >= 97 && r <= 122) {
			return r
		}
		return '_'
	}, name)
}

type testDef struct {
	Description  string         `json:"description"`
	BsonType     string         `json:"bson_type"`
	TestKey      string         `json:"test_key"`
	Valid        []*valid       `json:"valid"`
	DecodeErrors []*decodeError `json:"decodeErrors"`
	Deprecated   bool           `json:"deprecated"`
}

func (t *testDef) GoType() string {
	switch t.BsonType {
	case "0x01":
		return "float64"
	case "0x02":
		return "string"
	case "0x03":
		return "bson.D"
	case "0x04":
		return "[]interface{}"
	case "0x05":
		return "[]byte"
	case "0x07":
		return "bson.ObjectId"
	case "0x08":
		return "bool"
	case "0x09":
		return "time.Time"
	case "0x0E":
		return "string"
	case "0x10":
		return "int32"
	case "0x12":
		return "int64"
	case "0x13":
		return "bson.Decimal"
	default:
		return "interface{}"
	}
}

type valid struct {
	Description   string `json:"description"`
	Bson          string `json:"bson"`
	CanonicalBson string `json:"canonical_bson"`

	Name       string
	StructTest bool
	TestDef    *testDef
}

type decodeError struct {
	Description string `json:"description"`
	Bson        string `json:"bson"`

	Name string
}