|
| 1 | +// SPDX-FileCopyrightText: 2026 SUSE LLC |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +package get |
| 6 | + |
| 7 | +import ( |
| 8 | + "net/http" |
| 9 | + "net/http/httptest" |
| 10 | + "strings" |
| 11 | + "testing" |
| 12 | + |
| 13 | + "github.com/uyuni-project/uyuni-tools/shared/api" |
| 14 | + "github.com/uyuni-project/uyuni-tools/shared/types" |
| 15 | +) |
| 16 | + |
| 17 | +var mockSystemJSON = `{ |
| 18 | + "success": true, |
| 19 | + "result": [ |
| 20 | + { |
| 21 | + "id": 1001, |
| 22 | + "name": "test-system.uy", |
| 23 | + "last_checkin": "2026-03-19 14:00:00", |
| 24 | + "created": "2026-03-19 13:00:00" |
| 25 | + } |
| 26 | + ] |
| 27 | +}` |
| 28 | + |
| 29 | +func TestRunSystem_JSON(t *testing.T) { |
| 30 | + // 1. Create a mocked TLS server that simulates the Uyuni API |
| 31 | + ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 32 | + // Mock the login authentication endpoint |
| 33 | + if strings.HasSuffix(r.URL.Path, "auth/login") { |
| 34 | + w.Header().Set("Set-Cookie", "pxt-session-cookie=mock_cookie; Max-Age=3600") |
| 35 | + w.WriteHeader(http.StatusOK) |
| 36 | + _, _ = w.Write([]byte(`{"success": true, "result": "mock_cookie"}`)) |
| 37 | + return |
| 38 | + } |
| 39 | + |
| 40 | + // Mock the actual system endpoint |
| 41 | + if strings.HasSuffix(r.URL.Path, "system/listSystems") { |
| 42 | + w.WriteHeader(http.StatusOK) |
| 43 | + _, _ = w.Write([]byte(mockSystemJSON)) |
| 44 | + return |
| 45 | + } |
| 46 | + |
| 47 | + w.WriteHeader(http.StatusNotFound) |
| 48 | + })) |
| 49 | + defer ts.Close() |
| 50 | + |
| 51 | + // 2. Configure the mocked API Server details |
| 52 | + mockHost := strings.TrimPrefix(ts.URL, "https://") |
| 53 | + |
| 54 | + globalFlags := &types.GlobalFlags{} |
| 55 | + flags := &getFlags{ |
| 56 | + ConnectionDetails: api.ConnectionDetails{ |
| 57 | + Server: mockHost, |
| 58 | + User: "admin", |
| 59 | + Password: "mockpassword", |
| 60 | + Insecure: true, |
| 61 | + }, |
| 62 | + OutputFormat: "json", |
| 63 | + } |
| 64 | + |
| 65 | + // 3. Execute the function natively |
| 66 | + cmd := newSystemCommand(globalFlags, flags) |
| 67 | + err := cmd.RunE(cmd, []string{}) |
| 68 | + |
| 69 | + // 4. Assert no error occurred during authentication, fetching, and formatting |
| 70 | + if err != nil { |
| 71 | + t.Fatalf("Expected no error, got: %v", err) |
| 72 | + } |
| 73 | +} |
0 commit comments