blob: a4ad90a3b1a400a4ba6fae045435ebb5b81c9c98 [file] [log] [blame]
Marcel van Lohuizen240a9952019-08-05 10:29:13 +02001// Copyright 2019 CUE Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package gocode
16
17import (
18 "bytes"
19 "flag"
20 "io/ioutil"
21 "os"
22 "path/filepath"
23 "regexp"
24 "testing"
25
26 "cuelang.org/go/cue"
27 "cuelang.org/go/cue/errors"
28 "cuelang.org/go/cue/load"
Marcel van Lohuizenbfbcd502019-08-23 09:14:15 +020029 "github.com/kylelemons/godebug/diff"
Marcel van Lohuizen240a9952019-08-05 10:29:13 +020030)
31
32var update = flag.Bool("update", false, "update test files")
33
34func TestGenerate(t *testing.T) {
35 dirs, err := ioutil.ReadDir("testdata")
36 if err != nil {
37 t.Fatal(err)
38 }
39
40 cwd, err := os.Getwd()
41 if err != nil {
42 t.Fatal(err)
43 }
44
45 for _, d := range dirs {
46 if !d.IsDir() {
47 continue
48 }
49 t.Run(d.Name(), func(t *testing.T) {
50 dir := filepath.Join(cwd, "testdata")
51 pkg := "." + string(filepath.Separator) + d.Name()
52 inst := cue.Build(load.Instances([]string{pkg}, &load.Config{
53 Dir: dir,
54 ModuleRoot: dir,
55 Module: "cuelang.org/go/encoding/gocode/testdata",
56 }))[0]
57 if err := inst.Err; err != nil {
58 t.Fatal(err)
59 }
60
61 goPkg := "./testdata/" + d.Name()
62 b, err := Generate(goPkg, inst, nil)
63 if err != nil {
64 t.Fatal(errStr(err))
65 }
Marcel van Lohuizen240a9952019-08-05 10:29:13 +020066
67 goFile := filepath.Join("testdata", d.Name(), "cue_gen.go")
68 if *update {
69 _ = ioutil.WriteFile(goFile, b, 0644)
70 return
71 }
Marcel van Lohuizenbfbcd502019-08-23 09:14:15 +020072
73 want, err := ioutil.ReadFile(goFile)
74 if err != nil {
75 t.Fatal(err)
76 }
77
78 if d := diff.Diff(string(want), string(b)); d != "" {
79 t.Errorf("files differ:\n%v", d)
80 }
Marcel van Lohuizen240a9952019-08-05 10:29:13 +020081 })
82 }
83}
84
85func errStr(err error) string {
86 if err == nil {
87 return "nil"
88 }
89 buf := &bytes.Buffer{}
90 errors.Print(buf, err, nil)
91 r := regexp.MustCompile(`.cue:\d+:\d+`)
92 return r.ReplaceAllString(buf.String(), ".cue:x:x")
93}