secret_locks_test.go 2.1 KB

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