...

Source file src/go.etcd.io/etcd/client/pkg/v3/fileutil/lock_test.go

Documentation: go.etcd.io/etcd/client/pkg/v3/fileutil

     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  
    15  package fileutil
    16  
    17  import (
    18  	"io/ioutil"
    19  	"os"
    20  	"testing"
    21  	"time"
    22  )
    23  
    24  func TestLockAndUnlock(t *testing.T) {
    25  	f, err := ioutil.TempFile("", "lock")
    26  	if err != nil {
    27  		t.Fatal(err)
    28  	}
    29  	f.Close()
    30  	defer func() {
    31  		err = os.Remove(f.Name())
    32  		if err != nil {
    33  			t.Fatal(err)
    34  		}
    35  	}()
    36  
    37  	// lock the file
    38  	l, err := LockFile(f.Name(), os.O_WRONLY, PrivateFileMode)
    39  	if err != nil {
    40  		t.Fatal(err)
    41  	}
    42  
    43  	// try lock a locked file
    44  	if _, err = TryLockFile(f.Name(), os.O_WRONLY, PrivateFileMode); err != ErrLocked {
    45  		t.Fatal(err)
    46  	}
    47  
    48  	// unlock the file
    49  	if err = l.Close(); err != nil {
    50  		t.Fatal(err)
    51  	}
    52  
    53  	// try lock the unlocked file
    54  	dupl, err := TryLockFile(f.Name(), os.O_WRONLY, PrivateFileMode)
    55  	if err != nil {
    56  		t.Errorf("err = %v, want %v", err, nil)
    57  	}
    58  
    59  	// blocking on locked file
    60  	locked := make(chan struct{}, 1)
    61  	go func() {
    62  		bl, blerr := LockFile(f.Name(), os.O_WRONLY, PrivateFileMode)
    63  		if blerr != nil {
    64  			t.Error(blerr)
    65  		}
    66  		locked <- struct{}{}
    67  		if blerr = bl.Close(); blerr != nil {
    68  			t.Error(blerr)
    69  		}
    70  	}()
    71  
    72  	select {
    73  	case <-locked:
    74  		t.Error("unexpected unblocking")
    75  	case <-time.After(100 * time.Millisecond):
    76  	}
    77  
    78  	// unlock
    79  	if err = dupl.Close(); err != nil {
    80  		t.Fatal(err)
    81  	}
    82  
    83  	// the previously blocked routine should be unblocked
    84  	select {
    85  	case <-locked:
    86  	case <-time.After(1 * time.Second):
    87  		t.Error("unexpected blocking")
    88  	}
    89  }
    90  

View as plain text