...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package main
17
18 import (
19 "bytes"
20 "fmt"
21 "text/template"
22 )
23
24
25 type workflowTestCodeGenerator struct {
26
27 chaosTypes []string
28 }
29
30 func newWorkflowTestCodeGenerator(types []string) *workflowTestCodeGenerator {
31 return &workflowTestCodeGenerator{chaosTypes: types}
32 }
33
34 func (it *workflowTestCodeGenerator) AppendTypes(typeName string) {
35 it.chaosTypes = append(it.chaosTypes, typeName)
36 }
37
38 func (it *workflowTestCodeGenerator) Render() string {
39 imports := `import (
40 . "github.com/onsi/gomega"
41 "testing"
42 )
43 `
44 testMethods := ""
45 for _, typeName := range it.chaosTypes {
46 testMethods += generateTestTemplateEntry(typeName)
47 }
48 return fmt.Sprintf(`%s
49 // this file tests the coupling with all kinds map and each TemplateType
50 %s
51 %s
52 `,
53 boilerplate,
54 imports,
55 testMethods,
56 )
57 }
58
59 const testEntryTemplate = `func TestChaosKindMapShouldContains{{.Type}}(t *testing.T) {
60 g := NewGomegaWithT(t)
61 var requiredType TemplateType
62 requiredType = Type{{.Type}}
63
64 _, ok := all.kinds[string(requiredType)]
65 g.Expect(ok).To(Equal(true), "all kinds map should contains this type", requiredType)
66 }
67 `
68
69 func generateTestTemplateEntry(typeName string) string {
70 tmpl, err := template.New("testEntryTemplate").Parse(testEntryTemplate)
71 if err != nil {
72 log.Error(err, "fail to build template")
73 return ""
74 }
75
76 buf := new(bytes.Buffer)
77 err = tmpl.Execute(buf, &metadata{
78 Type: typeName,
79 })
80 if err != nil {
81 log.Error(err, "fail to execute template")
82 return ""
83 }
84
85 return buf.String()
86 }
87