kubetestgen.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "flag"
  16. "fmt"
  17. "os"
  18. "sort"
  19. "strings"
  20. "github.com/go-openapi/analysis"
  21. "github.com/go-openapi/loads"
  22. "github.com/go-openapi/spec"
  23. "gopkg.in/yaml.v2"
  24. )
  25. type options struct {
  26. schemaPath string
  27. resource string
  28. area string
  29. behaviorsDir string
  30. }
  31. func parseFlags() *options {
  32. o := &options{}
  33. flag.StringVar(&o.schemaPath, "schema", "", "Path to the OpenAPI schema")
  34. flag.StringVar(&o.resource, "resource", ".*", "Resource name")
  35. flag.StringVar(&o.area, "area", "default", "Area name to use")
  36. flag.StringVar(&o.behaviorsDir, "dir", "../behaviors/", "Path to the behaviors directory")
  37. flag.Parse()
  38. return o
  39. }
  40. var defMap map[string]analysis.SchemaRef
  41. func main() {
  42. defMap = make(map[string]analysis.SchemaRef)
  43. o := parseFlags()
  44. d, err := loads.JSONSpec(o.schemaPath)
  45. if err != nil {
  46. fmt.Printf("ERROR: %s\n", err.Error())
  47. os.Exit(1)
  48. }
  49. defs := d.Analyzer.AllDefinitions()
  50. sort.Slice(defs, func(i, j int) bool { return defs[i].Name < defs[j].Name })
  51. for _, d := range defs {
  52. if !d.TopLevel {
  53. continue
  54. }
  55. defMap[d.Ref.String()] = d
  56. }
  57. var suites []Suite
  58. var suiteMapping = make(map[string]*Suite)
  59. for _, v := range defs {
  60. if !v.TopLevel || o.resource != v.Name {
  61. continue
  62. }
  63. name := trimObjectName(v.Name)
  64. defaultsuite := Suite{
  65. Suite: o.area + "/spec",
  66. Description: "Base suite for " + o.area,
  67. Behaviors: []Behavior{},
  68. }
  69. _ = defaultsuite
  70. for p, propSchema := range v.Schema.Properties {
  71. id := o.area + p + "/"
  72. if propSchema.Ref.String() != "" || propSchema.Type[0] == "array" {
  73. if _, ok := suiteMapping[id]; !ok {
  74. newsuite := Suite{
  75. Suite: o.area + "/" + p,
  76. Description: "Suite for " + o.area + "/" + p,
  77. Behaviors: []Behavior{},
  78. }
  79. suiteMapping[id] = &newsuite
  80. }
  81. behaviors := suiteMapping[id].Behaviors
  82. behaviors = append(behaviors, schemaBehavior(o.area, name, p, propSchema)...)
  83. suiteMapping[id].Behaviors = behaviors
  84. } else {
  85. if _, ok := suiteMapping["default"]; !ok {
  86. newsuite := Suite{
  87. Suite: o.area + "/spec",
  88. Description: "Base suite for " + o.area,
  89. Behaviors: []Behavior{},
  90. }
  91. suiteMapping["default"] = &newsuite
  92. }
  93. behaviors := suiteMapping["default"].Behaviors
  94. behaviors = append(behaviors, schemaBehavior(o.area, name, p, propSchema)...)
  95. suiteMapping["default"].Behaviors = behaviors
  96. }
  97. }
  98. for _, v := range suiteMapping {
  99. suites = append(suites, *v)
  100. }
  101. break
  102. }
  103. var area Area = Area{o.area, suites}
  104. countFields(suites)
  105. printYAML(o.behaviorsDir+o.area, area)
  106. }
  107. func printYAML(fileName string, areaO Area) {
  108. f, err := os.Create(fileName + ".yaml")
  109. if err != nil {
  110. fmt.Printf("ERROR: %s\n", err.Error())
  111. os.Exit(1)
  112. }
  113. defer f.Close()
  114. y, err := yaml.Marshal(areaO)
  115. if err != nil {
  116. fmt.Printf("ERROR: %s\n", err.Error())
  117. os.Exit(1)
  118. }
  119. _, err = f.WriteString(string(y))
  120. if err != nil {
  121. fmt.Printf("ERROR: %s\n", err.Error())
  122. os.Exit(1)
  123. }
  124. }
  125. func countFields(suites []Suite) {
  126. var fieldsMapping map[string]int
  127. fieldsMapping = make(map[string]int)
  128. for _, suite := range suites {
  129. for _, behavior := range suite.Behaviors {
  130. if _, exists := fieldsMapping[behavior.APIType]; exists {
  131. fieldsMapping[behavior.APIType]++
  132. } else {
  133. fieldsMapping[behavior.APIType] = 1
  134. }
  135. }
  136. }
  137. for k, v := range fieldsMapping {
  138. fmt.Printf("Type %v, Count %v\n", k, v)
  139. }
  140. }
  141. func trimObjectName(name string) string {
  142. if strings.Index(name, "#/definitions/") == 0 {
  143. name = name[len("#/definitions/"):]
  144. }
  145. if strings.Index(name, "io.k8s.api.") == 0 {
  146. return name[len("io.k8s.api."):]
  147. }
  148. return name
  149. }
  150. func objectBehaviors(id string, s *spec.Schema) []Behavior {
  151. if strings.Contains(id, "openAPIV3Schema") || strings.Contains(id, "JSONSchema") || strings.Contains(s.Ref.String(), "JSONSchema") {
  152. return []Behavior{}
  153. }
  154. ref, ok := defMap[s.Ref.String()]
  155. if !ok {
  156. return []Behavior{}
  157. }
  158. return schemaBehaviors(id, trimObjectName(ref.Name), ref.Schema)
  159. }
  160. func schemaBehaviors(base, apiObject string, s *spec.Schema) []Behavior {
  161. var behaviors []Behavior
  162. for p, propSchema := range s.Properties {
  163. b := schemaBehavior(base, apiObject, p, propSchema)
  164. behaviors = append(behaviors, b...)
  165. }
  166. return behaviors
  167. }
  168. func schemaBehavior(base, apiObject, p string, propSchema spec.Schema) []Behavior {
  169. id := strings.Join([]string{base, p}, "/")
  170. if propSchema.Ref.String() != "" {
  171. if apiObject == trimObjectName(propSchema.Ref.String()) {
  172. return []Behavior{}
  173. }
  174. return objectBehaviors(id, &propSchema)
  175. }
  176. var b []Behavior
  177. switch propSchema.Type[0] {
  178. case "array":
  179. b = objectBehaviors(id, propSchema.Items.Schema)
  180. case "boolean":
  181. b = []Behavior{
  182. {
  183. ID: id,
  184. APIObject: apiObject,
  185. APIField: p,
  186. APIType: propSchema.Type[0],
  187. Description: "Boolean set to true. " + propSchema.Description,
  188. },
  189. {
  190. ID: id,
  191. APIObject: apiObject,
  192. APIField: p,
  193. APIType: propSchema.Type[0],
  194. Description: "Boolean set to false. " + propSchema.Description,
  195. },
  196. }
  197. default:
  198. b = []Behavior{{
  199. ID: id,
  200. APIObject: apiObject,
  201. APIField: p,
  202. APIType: propSchema.Type[0],
  203. Description: propSchema.Description,
  204. }}
  205. }
  206. return b
  207. }