edit_test.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 edit
  14. import (
  15. "bytes"
  16. "encoding/json"
  17. "io"
  18. "io/ioutil"
  19. "net/http"
  20. "net/http/httptest"
  21. "os"
  22. "path/filepath"
  23. "strings"
  24. "testing"
  25. "github.com/spf13/cobra"
  26. yaml "gopkg.in/yaml.v2"
  27. "k8s.io/apimachinery/pkg/runtime/schema"
  28. "k8s.io/apimachinery/pkg/util/diff"
  29. "k8s.io/apimachinery/pkg/util/sets"
  30. "k8s.io/cli-runtime/pkg/genericclioptions"
  31. "k8s.io/cli-runtime/pkg/resource"
  32. "k8s.io/client-go/rest/fake"
  33. "k8s.io/kubernetes/pkg/kubectl/cmd/apply"
  34. "k8s.io/kubernetes/pkg/kubectl/cmd/create"
  35. cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
  36. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  37. )
  38. type EditTestCase struct {
  39. Description string `yaml:"description"`
  40. // create or edit
  41. Mode string `yaml:"mode"`
  42. Args []string `yaml:"args"`
  43. Filename string `yaml:"filename"`
  44. Output string `yaml:"outputFormat"`
  45. OutputPatch string `yaml:"outputPatch"`
  46. SaveConfig string `yaml:"saveConfig"`
  47. Namespace string `yaml:"namespace"`
  48. ExpectedStdout []string `yaml:"expectedStdout"`
  49. ExpectedStderr []string `yaml:"expectedStderr"`
  50. ExpectedExitCode int `yaml:"expectedExitCode"`
  51. Steps []EditStep `yaml:"steps"`
  52. }
  53. type EditStep struct {
  54. // edit or request
  55. StepType string `yaml:"type"`
  56. // only applies to request
  57. RequestMethod string `yaml:"expectedMethod,omitempty"`
  58. RequestPath string `yaml:"expectedPath,omitempty"`
  59. RequestContentType string `yaml:"expectedContentType,omitempty"`
  60. Input string `yaml:"expectedInput"`
  61. // only applies to request
  62. ResponseStatusCode int `yaml:"resultingStatusCode,omitempty"`
  63. Output string `yaml:"resultingOutput"`
  64. }
  65. func TestEdit(t *testing.T) {
  66. var (
  67. name string
  68. testcase EditTestCase
  69. i int
  70. err error
  71. )
  72. const updateEnvVar = "UPDATE_EDIT_FIXTURE_DATA"
  73. updateInputFixtures := os.Getenv(updateEnvVar) == "true"
  74. reqResp := func(req *http.Request) (*http.Response, error) {
  75. defer func() { i++ }()
  76. if i > len(testcase.Steps)-1 {
  77. t.Fatalf("%s, step %d: more requests than steps, got %s %s", name, i, req.Method, req.URL.Path)
  78. }
  79. step := testcase.Steps[i]
  80. body := []byte{}
  81. if req.Body != nil {
  82. body, err = ioutil.ReadAll(req.Body)
  83. if err != nil {
  84. t.Fatalf("%s, step %d: %v", name, i, err)
  85. }
  86. }
  87. inputFile := filepath.Join("testdata", "testcase-"+name, step.Input)
  88. expectedInput, err := ioutil.ReadFile(inputFile)
  89. if err != nil {
  90. t.Fatalf("%s, step %d: %v", name, i, err)
  91. }
  92. outputFile := filepath.Join("testdata", "testcase-"+name, step.Output)
  93. resultingOutput, err := ioutil.ReadFile(outputFile)
  94. if err != nil {
  95. t.Fatalf("%s, step %d: %v", name, i, err)
  96. }
  97. if req.Method == "POST" && req.URL.Path == "/callback" {
  98. if step.StepType != "edit" {
  99. t.Fatalf("%s, step %d: expected edit step, got %s %s", name, i, req.Method, req.URL.Path)
  100. }
  101. if !bytes.Equal(body, expectedInput) {
  102. if updateInputFixtures {
  103. // Convenience to allow recapturing the input and persisting it here
  104. ioutil.WriteFile(inputFile, body, os.FileMode(0644))
  105. } else {
  106. t.Errorf("%s, step %d: diff in edit content:\n%s", name, i, diff.StringDiff(string(body), string(expectedInput)))
  107. t.Logf("If the change in input is expected, rerun tests with %s=true to update input fixtures", updateEnvVar)
  108. }
  109. }
  110. return &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader(resultingOutput))}, nil
  111. }
  112. if step.StepType != "request" {
  113. t.Fatalf("%s, step %d: expected request step, got %s %s", name, i, req.Method, req.URL.Path)
  114. }
  115. body = tryIndent(body)
  116. expectedInput = tryIndent(expectedInput)
  117. if req.Method != step.RequestMethod || req.URL.Path != step.RequestPath || req.Header.Get("Content-Type") != step.RequestContentType {
  118. t.Fatalf(
  119. "%s, step %d: expected \n%s %s (content-type=%s)\ngot\n%s %s (content-type=%s)", name, i,
  120. step.RequestMethod, step.RequestPath, step.RequestContentType,
  121. req.Method, req.URL.Path, req.Header.Get("Content-Type"),
  122. )
  123. }
  124. if !bytes.Equal(body, expectedInput) {
  125. if updateInputFixtures {
  126. // Convenience to allow recapturing the input and persisting it here
  127. ioutil.WriteFile(inputFile, body, os.FileMode(0644))
  128. } else {
  129. t.Errorf("%s, step %d: diff in edit content:\n%s", name, i, diff.StringDiff(string(body), string(expectedInput)))
  130. t.Logf("If the change in input is expected, rerun tests with %s=true to update input fixtures", updateEnvVar)
  131. }
  132. }
  133. return &http.Response{StatusCode: step.ResponseStatusCode, Header: cmdtesting.DefaultHeader(), Body: ioutil.NopCloser(bytes.NewReader(resultingOutput))}, nil
  134. }
  135. handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  136. resp, _ := reqResp(req)
  137. for k, vs := range resp.Header {
  138. w.Header().Del(k)
  139. for _, v := range vs {
  140. w.Header().Add(k, v)
  141. }
  142. }
  143. w.WriteHeader(resp.StatusCode)
  144. io.Copy(w, resp.Body)
  145. })
  146. server := httptest.NewServer(handler)
  147. defer server.Close()
  148. os.Setenv("KUBE_EDITOR", "testdata/test_editor.sh")
  149. os.Setenv("KUBE_EDITOR_CALLBACK", server.URL+"/callback")
  150. testcases := sets.NewString()
  151. filepath.Walk("testdata", func(path string, info os.FileInfo, err error) error {
  152. if err != nil {
  153. return err
  154. }
  155. if path == "testdata" {
  156. return nil
  157. }
  158. name := filepath.Base(path)
  159. if info.IsDir() {
  160. if strings.HasPrefix(name, "testcase-") {
  161. testcases.Insert(strings.TrimPrefix(name, "testcase-"))
  162. }
  163. return filepath.SkipDir
  164. }
  165. return nil
  166. })
  167. // sanity check that we found the right folder
  168. if !testcases.Has("create-list") {
  169. t.Fatalf("Error locating edit testcases")
  170. }
  171. for _, testcaseName := range testcases.List() {
  172. t.Run(testcaseName, func(t *testing.T) {
  173. i = 0
  174. name = testcaseName
  175. testcase = EditTestCase{}
  176. testcaseDir := filepath.Join("testdata", "testcase-"+name)
  177. testcaseData, err := ioutil.ReadFile(filepath.Join(testcaseDir, "test.yaml"))
  178. if err != nil {
  179. t.Fatalf("%s: %v", name, err)
  180. }
  181. if err := yaml.Unmarshal(testcaseData, &testcase); err != nil {
  182. t.Fatalf("%s: %v", name, err)
  183. }
  184. tf := cmdtesting.NewTestFactory()
  185. defer tf.Cleanup()
  186. tf.UnstructuredClientForMappingFunc = func(gv schema.GroupVersion) (resource.RESTClient, error) {
  187. versionedAPIPath := ""
  188. if gv.Group == "" {
  189. versionedAPIPath = "/api/" + gv.Version
  190. } else {
  191. versionedAPIPath = "/apis/" + gv.Group + "/" + gv.Version
  192. }
  193. return &fake.RESTClient{
  194. VersionedAPIPath: versionedAPIPath,
  195. NegotiatedSerializer: resource.UnstructuredPlusDefaultContentConfig().NegotiatedSerializer,
  196. Client: fake.CreateHTTPClient(reqResp),
  197. }, nil
  198. }
  199. tf.WithNamespace(testcase.Namespace)
  200. tf.ClientConfigVal = cmdtesting.DefaultClientConfig()
  201. ioStreams, _, buf, errBuf := genericclioptions.NewTestIOStreams()
  202. var cmd *cobra.Command
  203. switch testcase.Mode {
  204. case "edit":
  205. cmd = NewCmdEdit(tf, ioStreams)
  206. case "create":
  207. cmd = create.NewCmdCreate(tf, ioStreams)
  208. cmd.Flags().Set("edit", "true")
  209. case "edit-last-applied":
  210. cmd = apply.NewCmdApplyEditLastApplied(tf, ioStreams)
  211. default:
  212. t.Fatalf("%s: unexpected mode %s", name, testcase.Mode)
  213. }
  214. if len(testcase.Filename) > 0 {
  215. cmd.Flags().Set("filename", filepath.Join(testcaseDir, testcase.Filename))
  216. }
  217. if len(testcase.Output) > 0 {
  218. cmd.Flags().Set("output", testcase.Output)
  219. }
  220. if len(testcase.OutputPatch) > 0 {
  221. cmd.Flags().Set("output-patch", testcase.OutputPatch)
  222. }
  223. if len(testcase.SaveConfig) > 0 {
  224. cmd.Flags().Set("save-config", testcase.SaveConfig)
  225. }
  226. cmdutil.BehaviorOnFatal(func(str string, code int) {
  227. errBuf.WriteString(str)
  228. if testcase.ExpectedExitCode != code {
  229. t.Errorf("%s: expected exit code %d, got %d: %s", name, testcase.ExpectedExitCode, code, str)
  230. }
  231. })
  232. cmd.Run(cmd, testcase.Args)
  233. stdout := buf.String()
  234. stderr := errBuf.String()
  235. for _, s := range testcase.ExpectedStdout {
  236. if !strings.Contains(stdout, s) {
  237. t.Errorf("%s: expected to see '%s' in stdout\n\nstdout:\n%s\n\nstderr:\n%s", name, s, stdout, stderr)
  238. }
  239. }
  240. for _, s := range testcase.ExpectedStderr {
  241. if !strings.Contains(stderr, s) {
  242. t.Errorf("%s: expected to see '%s' in stderr\n\nstdout:\n%s\n\nstderr:\n%s", name, s, stdout, stderr)
  243. }
  244. }
  245. if i < len(testcase.Steps) {
  246. t.Errorf("%s: saw %d steps, testcase included %d additional steps that were not exercised", name, i, len(testcase.Steps)-i)
  247. }
  248. })
  249. }
  250. }
  251. func tryIndent(data []byte) []byte {
  252. indented := &bytes.Buffer{}
  253. if err := json.Indent(indented, data, "", "\t"); err == nil {
  254. return indented.Bytes()
  255. }
  256. return data
  257. }