|
| 1 | +// SPDX-FileCopyrightText: 2026 SUSE LLC |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +package knownhost |
| 6 | + |
| 7 | +import ( |
| 8 | + "net/http" |
| 9 | + "testing" |
| 10 | + |
| 11 | + "github.com/uyuni-project/uyuni-tools/shared/api" |
| 12 | + "github.com/uyuni-project/uyuni-tools/shared/api/mocks" |
| 13 | + "github.com/uyuni-project/uyuni-tools/shared/testutils" |
| 14 | +) |
| 15 | + |
| 16 | +const user = "testUser" |
| 17 | +const password = "testPwd" |
| 18 | +const server = "testServer" |
| 19 | + |
| 20 | +var connectionDetails = &api.ConnectionDetails{User: user, Password: password, Server: server} |
| 21 | + |
| 22 | +// Test removeKnownHost function. |
| 23 | +func TestRemoveKnownHost(t *testing.T) { |
| 24 | + tests := []struct { |
| 25 | + name string |
| 26 | + hostname string |
| 27 | + port string |
| 28 | + statusCode int |
| 29 | + body string |
| 30 | + expectedError string |
| 31 | + }{ |
| 32 | + { |
| 33 | + name: "Test removing normal hostname and port", |
| 34 | + hostname: "client.uyuni.lan", |
| 35 | + port: "22", |
| 36 | + statusCode: 200, |
| 37 | + body: `{"success":true,"result":1}`, |
| 38 | + expectedError: "", |
| 39 | + }, |
| 40 | + { |
| 41 | + name: "Test removing escaped hostname and port", |
| 42 | + hostname: "escaped?client.uyuni.lan", |
| 43 | + port: "42", |
| 44 | + statusCode: 200, |
| 45 | + body: `{"success":true,"result":1}`, |
| 46 | + expectedError: "", |
| 47 | + }, |
| 48 | + { |
| 49 | + name: "Test removing an invalid port value", |
| 50 | + hostname: "myotherclient.uyuni.lan", |
| 51 | + port: "abc", |
| 52 | + statusCode: 400, |
| 53 | + body: `{"success":false,"message":"mocked error"}`, |
| 54 | + expectedError: "mocked error", |
| 55 | + }, |
| 56 | + } |
| 57 | + |
| 58 | + for _, tt := range tests { |
| 59 | + t.Run(tt.name, func(t *testing.T) { |
| 60 | + client, err := api.Init(connectionDetails) |
| 61 | + if err != nil { |
| 62 | + t.FailNow() |
| 63 | + } |
| 64 | + |
| 65 | + client.Client = &mocks.MockClient{ |
| 66 | + DoFunc: func(req *http.Request) (*http.Response, error) { |
| 67 | + testutils.AssertEquals(t, "Wrong URL called", req.URL.Path, "/rhn/manager/api/admin/ssh/removeKnownHost") |
| 68 | + |
| 69 | + query := req.URL.Query() |
| 70 | + testutils.AssertEquals(t, "The hostname is not properly passed", tt.hostname, query.Get("hostname")) |
| 71 | + testutils.AssertEquals(t, "The port is not properly passed", tt.port, query.Get("port")) |
| 72 | + |
| 73 | + return testutils.GetResponse(tt.statusCode, tt.body) |
| 74 | + }, |
| 75 | + } |
| 76 | + |
| 77 | + errorMessage := "" |
| 78 | + if err := removeKnownHost(client, tt.hostname, tt.port); err != nil { |
| 79 | + errorMessage = err.Error() |
| 80 | + } |
| 81 | + testutils.AssertStringContains(t, "Unexpected error message", errorMessage, tt.expectedError) |
| 82 | + }) |
| 83 | + } |
| 84 | +} |
0 commit comments