lock_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2015 The etcd Authors
  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 := LockFile(f.Name(), os.O_WRONLY, PrivateFileMode)
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. // try lock a locked file
  39. if _, err = TryLockFile(f.Name(), os.O_WRONLY, PrivateFileMode); err != ErrLocked {
  40. t.Fatal(err)
  41. }
  42. // unlock the file
  43. if err = l.Close(); err != nil {
  44. t.Fatal(err)
  45. }
  46. // try lock the unlocked file
  47. dupl, err := TryLockFile(f.Name(), os.O_WRONLY, PrivateFileMode)
  48. if err != nil {
  49. t.Errorf("err = %v, want %v", err, nil)
  50. }
  51. // blocking on locked file
  52. locked := make(chan struct{}, 1)
  53. go func() {
  54. bl, blerr := LockFile(f.Name(), os.O_WRONLY, PrivateFileMode)
  55. if blerr != nil {
  56. t.Fatal(blerr)
  57. }
  58. locked <- struct{}{}
  59. if blerr = bl.Close(); blerr != nil {
  60. t.Fatal(blerr)
  61. }
  62. }()
  63. select {
  64. case <-locked:
  65. t.Error("unexpected unblocking")
  66. case <-time.After(100 * time.Millisecond):
  67. }
  68. // unlock
  69. if err = dupl.Close(); err != nil {
  70. t.Fatal(err)
  71. }
  72. // the previously blocked routine should be unblocked
  73. select {
  74. case <-locked:
  75. case <-time.After(1 * time.Second):
  76. t.Error("unexpected blocking")
  77. }
  78. }