keyring_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package agent
  5. import "testing"
  6. func addTestKey(t *testing.T, a Agent, keyName string) {
  7. err := a.Add(AddedKey{
  8. PrivateKey: testPrivateKeys[keyName],
  9. Comment: keyName,
  10. })
  11. if err != nil {
  12. t.Fatalf("failed to add key %q: %v", keyName, err)
  13. }
  14. }
  15. func removeTestKey(t *testing.T, a Agent, keyName string) {
  16. err := a.Remove(testPublicKeys[keyName])
  17. if err != nil {
  18. t.Fatalf("failed to remove key %q: %v", keyName, err)
  19. }
  20. }
  21. func validateListedKeys(t *testing.T, a Agent, expectedKeys []string) {
  22. listedKeys, err := a.List()
  23. if err != nil {
  24. t.Fatalf("failed to list keys: %v", err)
  25. return
  26. }
  27. actualKeys := make(map[string]bool)
  28. for _, key := range listedKeys {
  29. actualKeys[key.Comment] = true
  30. }
  31. matchedKeys := make(map[string]bool)
  32. for _, expectedKey := range expectedKeys {
  33. if !actualKeys[expectedKey] {
  34. t.Fatalf("expected key %q, but was not found", expectedKey)
  35. } else {
  36. matchedKeys[expectedKey] = true
  37. }
  38. }
  39. for actualKey := range actualKeys {
  40. if !matchedKeys[actualKey] {
  41. t.Fatalf("key %q was found, but was not expected", actualKey)
  42. }
  43. }
  44. }
  45. func TestKeyringAddingAndRemoving(t *testing.T) {
  46. keyNames := []string{"dsa", "ecdsa", "rsa", "user"}
  47. // add all test private keys
  48. k := NewKeyring()
  49. for _, keyName := range keyNames {
  50. addTestKey(t, k, keyName)
  51. }
  52. validateListedKeys(t, k, keyNames)
  53. // remove a key in the middle
  54. keyToRemove := keyNames[1]
  55. keyNames = append(keyNames[:1], keyNames[2:]...)
  56. removeTestKey(t, k, keyToRemove)
  57. validateListedKeys(t, k, keyNames)
  58. // remove all keys
  59. err := k.RemoveAll()
  60. if err != nil {
  61. t.Fatalf("failed to remove all keys: %v", err)
  62. }
  63. validateListedKeys(t, k, []string{})
  64. }