File: api_http_test.go

package info (click to toggle)
golang-github-crc-org-crc 2.34.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,548 kB
  • sloc: sh: 398; makefile: 326; javascript: 40
file content (506 lines) | stat: -rw-r--r-- 12,071 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
package api

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"net/http/httputil"
	"os"
	"strings"
	"testing"

	crcConfig "github.com/crc-org/crc/v2/pkg/crc/config"
	"github.com/crc-org/crc/v2/pkg/crc/constants"
	"github.com/crc-org/crc/v2/pkg/crc/machine/fakemachine"
	"github.com/crc-org/crc/v2/pkg/crc/preset"
	"github.com/crc-org/crc/v2/pkg/crc/version"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

type mockServer struct {
	*server
	client *fakemachine.Client
	config crcConfig.Storage
}

func createDummyPullSecret(t *testing.T) string {
	f, err := os.CreateTemp("", "kubeconfig")
	assert.NoError(t, err)
	_, err = f.WriteString(constants.OkdPullSecret)
	assert.NoError(t, err)
	err = f.Close()
	assert.NoError(t, err)

	return f.Name()
}

func removePullSecret(t *testing.T, server *mockServer) {
	_, err := server.config.Unset(crcConfig.PullSecretFile)
	assert.NoError(t, err)
}

func newMockServer(pullSecretPath string) *mockServer {
	fakeMachine := fakemachine.NewClient()

	config := setupNewInMemoryConfig()
	_, _ = config.Set(crcConfig.PullSecretFile, pullSecretPath)

	handler := NewHandler(config, fakeMachine, &mockLogger{}, &mockTelemetry{})

	return &mockServer{
		server: newServerWithRoutes(handler),
		client: fakeMachine,
		config: config,
	}
}

func sendRequest(handler http.Handler, request *request) *http.Response {
	url := fmt.Sprintf("/%s", request.resource)
	var data io.Reader
	if request.data != "" {
		data = strings.NewReader(request.data)
	} else {
		data = nil
	}

	req := httptest.NewRequest(request.httpMethod, url, data)
	req.Header.Set("Content-Type", "application/json")
	{
		requestDump, _ := httputil.DumpRequest(req, true)
		fmt.Println(string(requestDump))
	}
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)

	response := w.Result()
	{
		responseDump, _ := httputil.DumpResponse(response, true)
		fmt.Println(string(responseDump))
	}
	return response
}

type request struct {
	httpMethod string
	resource   string
	data       string
}

type response struct {
	statusCode int
	protoMajor int
	protoMinor int
	// headers
	body string
}

type testCase struct {
	preTestFunc func(t *testing.T, server *mockServer)
	request     request
	failRequest bool
	response    response
}

func get(resource string) request {
	return request{
		httpMethod: http.MethodGet,
		resource:   resource,
	}
}

func post(resource string) request {
	return request{
		httpMethod: http.MethodPost,
		resource:   resource,
	}
}

func deleteRequest(resource string) request {
	return request{
		httpMethod: http.MethodDelete,
		resource:   resource,
	}
}

func (req request) String() string {
	return fmt.Sprintf("%s /%s HTTP/1.1", req.httpMethod, req.resource)
}

func (req request) withBody(data string) request {
	req.data = data
	return req
}

func jSon(data string) response {
	return response{
		statusCode: 200,
		protoMajor: 1,
		protoMinor: 1,
		body:       data,
	}
}

func empty() response {
	return response{
		statusCode: 200,
		protoMajor: 1,
		protoMinor: 1,
	}
}

func httpError(statusCode int) response {
	return response{
		statusCode: statusCode,
		protoMajor: 1,
		protoMinor: 1,
	}
}

func (resp response) withBody(body string) response {
	resp.body = body
	return resp
}

var testCases = []testCase{
	// start
	{
		request:  post("start"),
		response: jSon(`{"Status":"","ClusterConfig":{"ClusterType":"openshift","ClusterCACert":"MIIDODCCAiCgAwIBAgIIRVfCKNUa1wIwDQYJ","KubeConfig":"/tmp/kubeconfig","KubeAdminPass":"foobar","ClusterAPI":"https://foo.testing:6443","WebConsoleURL":"https://console.foo.testing:6443","ProxyConfig":null},"KubeletStarted":true}`),
	},
	{
		request:  get("start"),
		response: jSon(`{"Status":"","ClusterConfig":{"ClusterType":"openshift","ClusterCACert":"MIIDODCCAiCgAwIBAgIIRVfCKNUa1wIwDQYJ","KubeConfig":"/tmp/kubeconfig","KubeAdminPass":"foobar","ClusterAPI":"https://foo.testing:6443","WebConsoleURL":"https://console.foo.testing:6443","ProxyConfig":null},"KubeletStarted":true}`),
	},

	// start with failure
	{
		request:     post("start"),
		failRequest: true,
		response:    httpError(500).withBody("Failed to start\n"),
	},
	{
		request:     get("start"),
		failRequest: true,
		response:    httpError(500).withBody("Failed to start\n"),
	},

	// stop
	{
		request:  post("stop"),
		response: empty(),
	},
	{
		request:  get("stop"),
		response: empty(),
	},

	// stop with failure
	{
		request:     post("stop"),
		failRequest: true,
		// error message comes from fakemachine
		response: httpError(500).withBody("stop failed\n"),
	},
	{
		request:     get("stop"),
		failRequest: true,
		// error message comes from fakemachine
		response: httpError(500).withBody("stop failed\n"),
	},

	// poweroff
	{
		request:  post("poweroff"),
		response: empty(),
	},

	// poweroff with failure
	{
		request:     post("poweroff"),
		failRequest: true,
		// error message comes from fakemachine
		response: httpError(500).withBody("poweroff failed\n"),
	},

	// status
	{
		request:  get("status"),
		response: jSon(`{"CrcStatus":"Running","OpenshiftStatus":"Running","OpenshiftVersion":"4.5.1","PodmanVersion":"3.3.1","DiskUse":10000000000,"DiskSize":20000000000,"RAMUse":1000,"RAMSize":2000,"Preset":"openshift"}`),
	},

	// status with failure
	{
		request:     get("status"),
		failRequest: true,
		// error message comes from fakemachine
		response: httpError(500).withBody("broken\n"),
	},

	// delete
	{
		request:  deleteRequest("delete"),
		response: empty(),
	},
	{
		request:  get("delete"),
		response: empty(),
	},

	// delete with failure
	{
		request:     deleteRequest("delete"),
		failRequest: true,
		// error message comes from fakemachine
		response: httpError(500).withBody("delete failed\n"),
	},
	{
		request:     get("delete"),
		failRequest: true,
		// error message comes from fakemachine
		response: httpError(500).withBody("delete failed\n"),
	},

	// version
	{
		request:  get("version"),
		response: jSon(fmt.Sprintf(`{"CrcVersion":"%s","CommitSha":"%s","OpenshiftVersion":"%s","PodmanVersion":"%s"}`, version.GetCRCVersion(), version.GetCommitSha(), version.GetBundleVersion(preset.OpenShift), version.GetBundleVersion(preset.Podman))),
	},

	// version never fails

	// webconsoleurl
	{
		request:  get("webconsoleurl"),
		response: jSon(`{"ClusterConfig":{"ClusterType":"openshift","ClusterCACert":"MIIDODCCAiCgAwIBAgIIRVfCKNUa1wIwDQYJ","KubeConfig":"/tmp/kubeconfig","KubeAdminPass":"foobar","ClusterAPI":"https://foo.testing:6443","WebConsoleURL":"https://console.foo.testing:6443","ProxyConfig":null},"State":"Running"}`),
	},

	// webconsoleurl with failure
	{
		request:     get("webconsoleurl"),
		failRequest: true,
		// error message comes from fakemachine
		response: httpError(500).withBody("console failed\n"),
	},

	// config
	{
		request:  get("config?cpus"),
		response: jSon(`{"Configs":{"cpus":4}}`),
	},
	{
		request:  post("config?cpus").withBody("xx"),
		response: httpError(500).withBody("invalid character 'x' looking for beginning of value\n"),
	},
	{
		request:  deleteRequest("config?cpus"),
		response: httpError(500).withBody("unexpected end of JSON input\n"),
	},
	{
		request:  get("config?cpus").withBody("xx"),
		response: jSon(`{"Configs":{"cpus":4}}`),
	},

	// logs
	{
		request:  get("logs"),
		response: jSon(`{"Messages":["message 1","message 2","message 3"]}`),
	},

	// logs never fails

	// telemetry
	{
		request:  get("telemetry"),
		response: httpError(500).withBody("unexpected end of JSON input\n"),
	},
	{
		request:  post("telemetry"),
		response: httpError(500).withBody("unexpected end of JSON input\n"),
	},

	// telemetry with failure
	{
		request:     get("telemetry"),
		failRequest: true,
		response:    httpError(500).withBody("unexpected end of JSON input\n"),
	},
	{
		request:     post("telemetry"),
		failRequest: true,
		response:    httpError(500).withBody("unexpected end of JSON input\n"),
	},

	// pull-secret
	{
		request: get("pull-secret"),
		// other 404 return "not found", and others "404 not found"
		response: empty().withBody(""),
	},
	{
		request:  post("pull-secret"),
		response: httpError(500).withBody("empty pull secret\n"),
	},

	// pull-secret with failure
	{
		preTestFunc: removePullSecret,
		request:     get("pull-secret"),
		failRequest: true,
		// other 404 return "not found", and others "404 not found"
		response: httpError(404),
	},
	{
		request:     post("pull-secret"),
		failRequest: true,
		response:    httpError(500).withBody("empty pull secret\n"),
	},

	// not found
	{
		request:  get("notfound"),
		response: httpError(404).withBody("Not Found\n"),
	},

	// config
	{
		request:  get("config?cpus"),
		response: jSon(`{"Configs":{"cpus":4}}`),
	},
}

var invalidHTTPMethods = []testCase{
	// start
	{
		request:  deleteRequest("start"),
		response: httpError(404).withBody("Not Found\n"),
	},

	// stop
	{
		request:  deleteRequest("stop"),
		response: httpError(404).withBody("Not Found\n"),
	},

	// poweroff
	{
		request:  get("poweroff"),
		response: httpError(404).withBody("Not Found\n"),
	},
	{
		request:  deleteRequest("poweroff"),
		response: httpError(404).withBody("Not Found\n"),
	},

	// status
	{
		request:  post("status"),
		response: httpError(404).withBody("Not Found\n"),
	},
	{
		request:  deleteRequest("status"),
		response: httpError(404).withBody("Not Found\n"),
	},

	// delete
	{
		request:  post("delete"),
		response: httpError(404).withBody("Not Found\n"),
	},

	// version
	{
		request:  post("version"),
		response: httpError(404).withBody("Not Found\n"),
	},
	{
		request:  deleteRequest("version"),
		response: httpError(404).withBody("Not Found\n"),
	},

	// webconsoleurl
	{
		request:  post("webconsoleurl"),
		response: httpError(404).withBody("Not Found\n"),
	},
	{
		request:  deleteRequest("webconsoleurl"),
		response: httpError(404).withBody("Not Found\n"),
	},

	// logs
	{
		request:  post("logs"),
		response: httpError(404).withBody("Not Found\n"),
	},
	{
		request:  deleteRequest("logs"),
		response: httpError(404).withBody("Not Found\n"),
	},

	// telemetry
	{
		request:  deleteRequest("telemetry"),
		response: httpError(404).withBody("Not Found\n"),
	},

	// pull-secret
	{
		request: deleteRequest("pull-secret"),
		// other 404 return "not found", and others "404 not found"
		response: httpError(404).withBody("Not Found\n"),
	},
}

func testOne(t *testing.T, testCase *testCase, server *mockServer) {
	server.client.Failing = testCase.failRequest
	if testCase.preTestFunc != nil {
		testCase.preTestFunc(t, server)
	}
	resp := sendRequest(server.Handler(), &testCase.request)

	require.Equal(t, testCase.response.statusCode, resp.StatusCode, testCase.request)
	require.Equal(t, testCase.response.protoMajor, resp.ProtoMajor, testCase.request)
	require.Equal(t, testCase.response.protoMinor, resp.ProtoMinor, testCase.request)
	body, err := io.ReadAll(resp.Body)
	require.NoError(t, err, testCase.request)
	require.Equal(t, testCase.response.body, string(body), testCase.request)
	fmt.Println("-----")
}

func TestRequests(t *testing.T) {
	pullSecretPath := createDummyPullSecret(t)
	defer os.Remove(pullSecretPath)
	server := newMockServer(pullSecretPath)

	for i := range testCases {
		testOne(t, &testCases[i], server)
	}

	for i := range invalidHTTPMethods {
		testOne(t, &testCases[i], server)
	}
}

func TestRoutes(t *testing.T) {
	// this checks that we have test cases for all routes registered with the `api` entrypoint

	var routes = map[string][]string{}
	for _, testCase := range testCases {
		// Add leading '/', remove trailing '?....'
		pattern := fmt.Sprintf("/%s", strings.SplitN(testCase.request.resource, "?", 2)[0])
		if _, ok := routes[pattern]; !ok {
			routes[pattern] = []string{}
		}
		routes[pattern] = append(routes[pattern], testCase.request.httpMethod)
	}

	server := newMockServer("")
	for pattern, methodMap := range server.routes {
		assert.Contains(t, routes, pattern)
		for method := range methodMap {
			assert.Contains(t, routes[pattern], method, "routes[%s][%s] is missing from the API testcases", pattern, method)
		}
	}
}