lock_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package fileutil
  15. import (
  16. "io/ioutil"
  17. "os"
  18. "testing"
  19. "time"
  20. )
  21. func TestLockAndUnlock(t *testing.T) {
  22. f, err := ioutil.TempFile("", "lock")
  23. if err != nil {
  24. t.Fatal(err)
  25. }
  26. f.Close()
  27. defer func() {
  28. err = os.Remove(f.Name())
  29. if err != nil {
  30. t.Fatal(err)
  31. }
  32. }()
  33. // lock the file
  34. l, err := NewLock(f.Name())
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. defer l.Destroy()
  39. err = l.Lock()
  40. if err != nil {
  41. t.Fatal(err)
  42. }
  43. // try lock a locked file
  44. dupl, err := NewLock(f.Name())
  45. if err != nil {
  46. t.Fatal(err)
  47. }
  48. err = dupl.TryLock()
  49. if err != ErrLocked {
  50. t.Errorf("err = %v, want %v", err, ErrLocked)
  51. }
  52. // unlock the file
  53. err = l.Unlock()
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. // try lock the unlocked file
  58. err = dupl.TryLock()
  59. if err != nil {
  60. t.Errorf("err = %v, want %v", err, nil)
  61. }
  62. defer dupl.Destroy()
  63. // blocking on locked file
  64. locked := make(chan struct{}, 1)
  65. go func() {
  66. l.Lock()
  67. locked <- struct{}{}
  68. }()
  69. select {
  70. case <-locked:
  71. t.Error("unexpected unblocking")
  72. case <-time.After(100 * time.Millisecond):
  73. }
  74. // unlock
  75. err = dupl.Unlock()
  76. if err != nil {
  77. t.Fatal(err)
  78. }
  79. // the previously blocked routine should be unblocked
  80. select {
  81. case <-locked:
  82. case <-time.After(1 * time.Second):
  83. t.Error("unexpected blocking")
  84. }
  85. }