|
| 1 | +package gerrit_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "strings" |
| 9 | + "testing" |
| 10 | +) |
| 11 | + |
| 12 | +// TestAddSSHKey tests the addition of an SSH key to an account. |
| 13 | +func TestAddSSHKey(t *testing.T) { |
| 14 | + setup() |
| 15 | + defer teardown() |
| 16 | + |
| 17 | + testMux.HandleFunc("/accounts/self/sshkeys", func(w http.ResponseWriter, r *http.Request) { |
| 18 | + // Ensure the request method is POST |
| 19 | + if r.Method != http.MethodPost { |
| 20 | + t.Errorf("Expected POST request, got %s", r.Method) |
| 21 | + } |
| 22 | + |
| 23 | + // Ensure Content-Type is text/plain |
| 24 | + if r.Header.Get("Content-Type") != "text/plain" { |
| 25 | + t.Errorf("Expected Content-Type 'text/plain', got %s", r.Header.Get("Content-Type")) |
| 26 | + } |
| 27 | + |
| 28 | + // Read body and validate SSH key |
| 29 | + expectedSSHKey := "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0T...YImydZAw== [email protected]" |
| 30 | + body, _ := io.ReadAll(r.Body) |
| 31 | + receivedSSHKey := strings.TrimSpace(string(body)) |
| 32 | + |
| 33 | + if receivedSSHKey != expectedSSHKey { |
| 34 | + t.Errorf("Expected SSH key '%s', but received '%s'", expectedSSHKey, receivedSSHKey) |
| 35 | + } |
| 36 | + |
| 37 | + // Mock successful JSON response |
| 38 | + w.Header().Set("Content-Type", "application/json; charset=UTF-8") |
| 39 | + w.WriteHeader(http.StatusOK) |
| 40 | + fmt.Fprint(w, `{ |
| 41 | + "seq": 2, |
| 42 | + "ssh_public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0T...YImydZAw== [email protected]", |
| 43 | + "encoded_key": "AAAAB3NzaC1yc2EAAAABIwAAAQEA0T...YImydZAw==", |
| 44 | + "algorithm": "ssh-rsa", |
| 45 | + |
| 46 | + "valid": true |
| 47 | + }`) |
| 48 | + }) |
| 49 | + |
| 50 | + ctx := context.Background() |
| 51 | + sshKey := "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0T...YImydZAw== [email protected]" |
| 52 | + |
| 53 | + // Use testClient.Accounts instead of undefined Accounts variable |
| 54 | + keyInfo, _, err := testClient.Accounts.AddSSHKey(ctx, "self", sshKey) |
| 55 | + if err != nil { |
| 56 | + t.Fatalf("AddSSHKey returned error: %v", err) |
| 57 | + } |
| 58 | + |
| 59 | + // Verify SSH key information in the response |
| 60 | + if keyInfo.SSHPublicKey != sshKey { |
| 61 | + t.Errorf("Expected SSH key '%s', got '%s'", sshKey, keyInfo.SSHPublicKey) |
| 62 | + } |
| 63 | + |
| 64 | + if keyInfo.Valid != true { |
| 65 | + t.Errorf("Expected key validity to be true, got false") |
| 66 | + } |
| 67 | + |
| 68 | + if keyInfo. Comment != "[email protected]" { |
| 69 | + t. Errorf( "Expected comment '[email protected]', got '%s'", keyInfo. Comment) |
| 70 | + } |
| 71 | +} |
0 commit comments