record.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. /*
  2. Copyright 2017 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. "bytes"
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "os"
  21. "strings"
  22. yaml "gopkg.in/yaml.v2"
  23. )
  24. type EditTestCase struct {
  25. Description string `yaml:"description"`
  26. // create or edit
  27. Mode string `yaml:"mode"`
  28. Args []string `yaml:"args"`
  29. Filename string `yaml:"filename"`
  30. Output string `yaml:"outputFormat"`
  31. Namespace string `yaml:"namespace"`
  32. ExpectedStdout []string `yaml:"expectedStdout"`
  33. ExpectedStderr []string `yaml:"expectedStderr"`
  34. ExpectedExitCode int `yaml:"expectedExitCode"`
  35. Steps []EditStep `yaml:"steps"`
  36. }
  37. type EditStep struct {
  38. // edit or request
  39. StepType string `yaml:"type"`
  40. // only applies to request
  41. RequestMethod string `yaml:"expectedMethod,omitempty"`
  42. RequestPath string `yaml:"expectedPath,omitempty"`
  43. RequestContentType string `yaml:"expectedContentType,omitempty"`
  44. Input string `yaml:"expectedInput"`
  45. // only applies to request
  46. ResponseStatusCode int `yaml:"resultingStatusCode,omitempty"`
  47. Output string `yaml:"resultingOutput"`
  48. }
  49. func main() {
  50. tc := &EditTestCase{
  51. Description: "add a testcase description",
  52. Mode: "edit",
  53. Args: []string{"set", "args"},
  54. ExpectedStdout: []string{"expected stdout substring"},
  55. ExpectedStderr: []string{"expected stderr substring"},
  56. }
  57. var currentStep *EditStep
  58. fmt.Println(http.ListenAndServe(":8081", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  59. // Record non-discovery things
  60. record := false
  61. switch segments := strings.Split(strings.Trim(req.URL.Path, "/"), "/"); segments[0] {
  62. case "api":
  63. // api, version
  64. record = len(segments) > 2
  65. case "apis":
  66. // apis, group, version
  67. record = len(segments) > 3
  68. case "callback":
  69. record = true
  70. }
  71. body, err := ioutil.ReadAll(req.Body)
  72. checkErr(err)
  73. switch m, p := req.Method, req.URL.Path; {
  74. case m == "POST" && p == "/callback/in":
  75. if currentStep != nil {
  76. panic("cannot post input with step already in progress")
  77. }
  78. filename := fmt.Sprintf("%d.original", len(tc.Steps))
  79. checkErr(ioutil.WriteFile(filename, body, os.FileMode(0755)))
  80. currentStep = &EditStep{StepType: "edit", Input: filename}
  81. case m == "POST" && p == "/callback/out":
  82. if currentStep == nil || currentStep.StepType != "edit" {
  83. panic("cannot post output without posting input first")
  84. }
  85. filename := fmt.Sprintf("%d.edited", len(tc.Steps))
  86. checkErr(ioutil.WriteFile(filename, body, os.FileMode(0755)))
  87. currentStep.Output = filename
  88. tc.Steps = append(tc.Steps, *currentStep)
  89. currentStep = nil
  90. default:
  91. if currentStep != nil {
  92. panic("cannot make request with step already in progress")
  93. }
  94. urlCopy := *req.URL
  95. urlCopy.Host = "localhost:8080"
  96. urlCopy.Scheme = "http"
  97. proxiedReq, err := http.NewRequest(req.Method, urlCopy.String(), bytes.NewReader(body))
  98. checkErr(err)
  99. proxiedReq.Header = req.Header
  100. resp, err := http.DefaultClient.Do(proxiedReq)
  101. checkErr(err)
  102. defer resp.Body.Close()
  103. bodyOut, err := ioutil.ReadAll(resp.Body)
  104. checkErr(err)
  105. for k, vs := range resp.Header {
  106. for _, v := range vs {
  107. w.Header().Add(k, v)
  108. }
  109. }
  110. w.WriteHeader(resp.StatusCode)
  111. w.Write(bodyOut)
  112. if record {
  113. infile := fmt.Sprintf("%d.request", len(tc.Steps))
  114. outfile := fmt.Sprintf("%d.response", len(tc.Steps))
  115. checkErr(ioutil.WriteFile(infile, tryIndent(body), os.FileMode(0755)))
  116. checkErr(ioutil.WriteFile(outfile, tryIndent(bodyOut), os.FileMode(0755)))
  117. tc.Steps = append(tc.Steps, EditStep{
  118. StepType: "request",
  119. Input: infile,
  120. Output: outfile,
  121. RequestContentType: req.Header.Get("Content-Type"),
  122. RequestMethod: req.Method,
  123. RequestPath: req.URL.Path,
  124. ResponseStatusCode: resp.StatusCode,
  125. })
  126. }
  127. }
  128. tcData, err := yaml.Marshal(tc)
  129. checkErr(err)
  130. checkErr(ioutil.WriteFile("test.yaml", tcData, os.FileMode(0755)))
  131. })))
  132. }
  133. func checkErr(err error) {
  134. if err != nil {
  135. panic(err)
  136. }
  137. }
  138. func tryIndent(data []byte) []byte {
  139. indented := &bytes.Buffer{}
  140. if err := json.Indent(indented, data, "", "\t"); err == nil {
  141. return indented.Bytes()
  142. }
  143. return data
  144. }