unlock_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package swarm
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "strings"
  7. "testing"
  8. "github.com/docker/docker/api/types"
  9. "github.com/docker/docker/api/types/swarm"
  10. "github.com/docker/docker/cli/internal/test"
  11. "github.com/docker/docker/pkg/testutil/assert"
  12. )
  13. func TestSwarmUnlockErrors(t *testing.T) {
  14. testCases := []struct {
  15. name string
  16. args []string
  17. input string
  18. swarmUnlockFunc func(req swarm.UnlockRequest) error
  19. infoFunc func() (types.Info, error)
  20. expectedError string
  21. }{
  22. {
  23. name: "too-many-args",
  24. args: []string{"foo"},
  25. expectedError: "accepts no argument(s)",
  26. },
  27. {
  28. name: "is-not-part-of-a-swarm",
  29. infoFunc: func() (types.Info, error) {
  30. return types.Info{
  31. Swarm: swarm.Info{
  32. LocalNodeState: swarm.LocalNodeStateInactive,
  33. },
  34. }, nil
  35. },
  36. expectedError: "This node is not part of a swarm",
  37. },
  38. {
  39. name: "is-not-locked",
  40. infoFunc: func() (types.Info, error) {
  41. return types.Info{
  42. Swarm: swarm.Info{
  43. LocalNodeState: swarm.LocalNodeStateActive,
  44. },
  45. }, nil
  46. },
  47. expectedError: "Error: swarm is not locked",
  48. },
  49. {
  50. name: "unlockrequest-failed",
  51. infoFunc: func() (types.Info, error) {
  52. return types.Info{
  53. Swarm: swarm.Info{
  54. LocalNodeState: swarm.LocalNodeStateLocked,
  55. },
  56. }, nil
  57. },
  58. swarmUnlockFunc: func(req swarm.UnlockRequest) error {
  59. return fmt.Errorf("error unlocking the swarm")
  60. },
  61. expectedError: "error unlocking the swarm",
  62. },
  63. }
  64. for _, tc := range testCases {
  65. buf := new(bytes.Buffer)
  66. cmd := newUnlockCommand(
  67. test.NewFakeCli(&fakeClient{
  68. infoFunc: tc.infoFunc,
  69. swarmUnlockFunc: tc.swarmUnlockFunc,
  70. }, buf))
  71. cmd.SetArgs(tc.args)
  72. cmd.SetOutput(ioutil.Discard)
  73. assert.Error(t, cmd.Execute(), tc.expectedError)
  74. }
  75. }
  76. func TestSwarmUnlock(t *testing.T) {
  77. input := "unlockKey"
  78. buf := new(bytes.Buffer)
  79. dockerCli := test.NewFakeCli(&fakeClient{
  80. infoFunc: func() (types.Info, error) {
  81. return types.Info{
  82. Swarm: swarm.Info{
  83. LocalNodeState: swarm.LocalNodeStateLocked,
  84. },
  85. }, nil
  86. },
  87. swarmUnlockFunc: func(req swarm.UnlockRequest) error {
  88. if req.UnlockKey != input {
  89. return fmt.Errorf("Invalid unlock key")
  90. }
  91. return nil
  92. },
  93. }, buf)
  94. dockerCli.SetIn(ioutil.NopCloser(strings.NewReader(input)))
  95. cmd := newUnlockCommand(dockerCli)
  96. assert.NilError(t, cmd.Execute())
  97. }