...
1
16
17 package clusterinfo
18
19 import (
20 "os"
21 "path"
22 "testing"
23
24 "k8s.io/cli-runtime/pkg/genericiooptions"
25 cmdtesting "k8s.io/kubectl/pkg/cmd/testing"
26 )
27
28 func TestSetupOutputWriterNoOp(t *testing.T) {
29 tests := []struct {
30 name string
31 outputWriter string
32 }{
33 {
34 name: "empty",
35 outputWriter: "",
36 },
37 {
38 name: "stdout",
39 outputWriter: "-",
40 },
41 }
42 for _, tt := range tests {
43 t.Run(tt.name, func(t *testing.T) {
44 _, _, buf, _ := genericiooptions.NewTestIOStreams()
45 f := cmdtesting.NewTestFactory()
46 defer f.Cleanup()
47
48 writer := setupOutputWriter(tt.outputWriter, buf, "/some/file/that/should/be/ignored", "")
49 if writer != buf {
50 t.Errorf("expected: %v, saw: %v", buf, writer)
51 }
52 })
53 }
54 }
55
56 func TestSetupOutputWriterFile(t *testing.T) {
57 file := "output"
58 extension := ".json"
59 dir, err := os.MkdirTemp(os.TempDir(), "out")
60 if err != nil {
61 t.Errorf("unexpected error: %v", err)
62 }
63 fullPath := path.Join(dir, file) + extension
64 defer os.RemoveAll(dir)
65
66 _, _, buf, _ := genericiooptions.NewTestIOStreams()
67 f := cmdtesting.NewTestFactory()
68 defer f.Cleanup()
69
70 writer := setupOutputWriter(dir, buf, file, extension)
71 if writer == buf {
72 t.Errorf("expected: %v, saw: %v", buf, writer)
73 }
74 output := "some data here"
75 writer.Write([]byte(output))
76
77 data, err := os.ReadFile(fullPath)
78 if err != nil {
79 t.Errorf("unexpected error: %v", err)
80 }
81 if string(data) != output {
82 t.Errorf("expected: %v, saw: %v", output, data)
83 }
84 }
85
View as plain text