26
"istio.io/istio/pkg/ptr"
27
"istio.io/istio/tests/util"
30
type pilotStubHandler struct {
32
States []pilotStubState
35
type pilotStubState struct {
43
func (p *pilotStubHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
45
if r.Method == p.States[0].wantMethod {
46
if r.URL.Path == p.States[0].wantPath {
48
body, _ := io.ReadAll(r.Body)
49
if err := util.Compare(body, p.States[0].wantBody); err == nil {
50
w.WriteHeader(p.States[0].StatusCode)
51
w.Write([]byte(p.States[0].Response))
53
w.WriteHeader(http.StatusBadRequest)
54
w.Write([]byte(fmt.Sprintf("wanted body %q got %q", string(p.States[0].wantBody), string(body))))
57
w.WriteHeader(http.StatusBadRequest)
58
w.Write([]byte(fmt.Sprintf("wanted path %q got %q", p.States[0].wantPath, r.URL.Path)))
61
w.WriteHeader(http.StatusBadRequest)
62
w.Write([]byte(fmt.Sprintf("wanted method %q got %q", p.States[0].wantMethod, r.Method)))
65
p.States[0] = ptr.Empty[pilotStubState]()
66
p.States = p.States[1:]
70
func Test_command_do(t *testing.T) {
76
pilotStates []pilotStubState
77
pilotNotReachable bool
81
name: "makes a request using passed method, url and body",
85
pilotStates: []pilotStubState{
86
{StatusCode: 200, Response: "fine", wantMethod: "POST", wantPath: "/want/path", wantBody: []byte("body")},
90
name: "adds / prefix to path if required",
94
pilotStates: []pilotStubState{
95
{StatusCode: 200, Response: "fine", wantMethod: "POST", wantPath: "/want/path", wantBody: []byte("body")},
99
name: "handles empty string body in args",
103
pilotStates: []pilotStubState{
104
{StatusCode: 200, Response: "fine", wantMethod: "GET", wantPath: "/want/path", wantBody: nil},
108
name: "doesn't error on 404",
112
pilotStates: []pilotStubState{
113
{StatusCode: 404, Response: "not-found", wantMethod: "GET", wantPath: "/want/path", wantBody: nil},
117
name: "errors if Pilot is unreachable",
120
pilotNotReachable: true,
124
name: "errors if Pilot responds with a non success status",
126
path: "/not/wanted/path",
128
pilotStates: []pilotStubState{
129
{StatusCode: 200, Response: "fine", wantMethod: "GET", wantPath: "/want/path", wantBody: nil},
134
for _, tt := range tests {
135
t.Run(tt.name, func(t *testing.T) {
136
pilotStub := httptest.NewServer(
137
&pilotStubHandler{States: tt.pilotStates},
139
stubURL, _ := url.Parse(pilotStub.URL)
140
if tt.pilotNotReachable {
141
stubURL, _ = url.Parse("http://notpilot")
144
Address: stubURL.Host,
145
Client: &http.Client{},
147
err := c.Do(tt.method, tt.path, tt.body)
148
if (err == nil) && tt.wantError {
149
t.Errorf("Expected an error but received none")
150
} else if (err != nil) && !tt.wantError {
151
t.Errorf("Unexpected err: %v", err)