secret_locks_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package locks
  13. import (
  14. "strings"
  15. "testing"
  16. )
  17. func TestTryLock(t *testing.T) {
  18. t.Parallel()
  19. providerName := "test-provider"
  20. secretName := "test-secret"
  21. tests := []struct {
  22. desc string
  23. preprocess func() chan error
  24. expected string
  25. }{
  26. {
  27. desc: "No conflict occurs and hold lock successfully",
  28. preprocess: func() chan error {
  29. ch := make(chan error)
  30. go func() {
  31. ch <- nil
  32. }()
  33. return ch
  34. },
  35. expected: "",
  36. },
  37. {
  38. desc: "Conflict occurs and cannot hold lock",
  39. preprocess: func() chan error {
  40. ch := make(chan error)
  41. go func() {
  42. _, err := TryLock(providerName, secretName)
  43. ch <- err
  44. }()
  45. return ch
  46. },
  47. expected: "failed to acquire lock: provider: test-provider, secret: test-secret: unable to access secret since it is locked",
  48. },
  49. }
  50. for _, tc := range tests {
  51. t.Run(tc.desc, func(t *testing.T) {
  52. // Evacuate the sharedLocks temporarily
  53. tmp := sharedLocks
  54. sharedLocks = &secretLocks{}
  55. defer func() {
  56. sharedLocks = tmp
  57. }()
  58. ch := tc.preprocess()
  59. err := <-ch
  60. if err != nil {
  61. t.Fatalf("preprocessing failed: %v", err)
  62. }
  63. _, got := TryLock(providerName, secretName)
  64. if got != nil {
  65. if tc.expected == "" {
  66. t.Fatalf("received an unexpected error: %v", got)
  67. }
  68. if !strings.Contains(got.Error(), tc.expected) {
  69. t.Fatalf("error %q is supposed to contain %q", got, tc.expected)
  70. }
  71. return
  72. }
  73. if tc.expected != "" {
  74. t.Fatal("expected to receive an error but got nil")
  75. }
  76. })
  77. }
  78. }