| 1 |
/* |
| 2 |
Copyright 2015 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package generator_test |
| 18 |
|
| 19 |
import ( |
| 20 |
"bytes" |
| 21 |
"strings" |
| 22 |
"testing" |
| 23 |
|
| 24 |
"k8s.io/gengo/generator" |
| 25 |
"k8s.io/gengo/namer" |
| 26 |
"k8s.io/gengo/parser" |
| 27 |
) |
| 28 |
|
| 29 |
func construct(t *testing.T, files map[string]string) *generator.Context { |
| 30 |
b := parser.New() |
| 31 |
for name, src := range files { |
| 32 |
if err := b.AddFileForTest("/tmp/"+name, name, []byte(src)); err != nil { |
| 33 |
t.Fatal(err) |
| 34 |
} |
| 35 |
} |
| 36 |
c, err := generator.NewContext(b, namer.NameSystems{ |
| 37 |
"public": namer.NewPublicNamer(0), |
| 38 |
"private": namer.NewPrivateNamer(0), |
| 39 |
}, "public") |
| 40 |
if err != nil { |
| 41 |
t.Fatal(err) |
| 42 |
} |
| 43 |
return c |
| 44 |
} |
| 45 |
|
| 46 |
func TestSnippetWriter(t *testing.T) { |
| 47 |
var structTest = map[string]string{ |
| 48 |
"base/foo/proto/foo.go": ` |
| 49 |
package foo |
| 50 |
|
| 51 |
// Blah is a test. |
| 52 |
// A test, I tell you. |
| 53 |
type Blah struct { |
| 54 |
// A is the first field. |
| 55 |
A int64 ` + "`" + `json:"a"` + "`" + ` |
| 56 |
|
| 57 |
// B is the second field. |
| 58 |
// Multiline comments work. |
| 59 |
B string ` + "`" + `json:"b"` + "`" + ` |
| 60 |
} |
| 61 |
`, |
| 62 |
} |
| 63 |
|
| 64 |
c := construct(t, structTest) |
| 65 |
b := &bytes.Buffer{} |
| 66 |
err := generator.NewSnippetWriter(b, c, "$", "$"). |
| 67 |
Do("$.|public$$.|private$", c.Order[0]). |
| 68 |
Error() |
| 69 |
if err != nil { |
| 70 |
t.Errorf("Unexpected error %v", err) |
| 71 |
} |
| 72 |
if e, a := "Blahblah", b.String(); e != a { |
| 73 |
t.Errorf("Expected %q, got %q", e, a) |
| 74 |
} |
| 75 |
|
| 76 |
err = generator.NewSnippetWriter(b, c, "$", "$"). |
| 77 |
Do("$.|public", c.Order[0]). |
| 78 |
Error() |
| 79 |
if err == nil { |
| 80 |
t.Errorf("expected error on invalid template") |
| 81 |
} else { |
| 82 |
// Dear reader, I apologize for making the worst change |
| 83 |
// detection test in the history of ever. |
| 84 |
if e, a := "snippet_writer_test.go", err.Error(); !strings.Contains(a, e) { |
| 85 |
t.Errorf("Expected %q but didn't find it in %q", e, a) |
| 86 |
} |
| 87 |
} |
| 88 |
} |