github.com/GuanceCloud/cliutils@v1.1.21/diskcache/lock_test.go (about)

     1  // Unless explicitly stated otherwise all files in this repository are licensed
     2  // under the MIT License.
     3  // This product includes software developed at Guance Cloud (https://www.guance.com/).
     4  // Copyright 2021-present Guance, Inc.
     5  
     6  package diskcache
     7  
     8  import (
     9  	"os"
    10  	"runtime"
    11  	"sync"
    12  	T "testing"
    13  	"time"
    14  
    15  	"github.com/stretchr/testify/assert"
    16  )
    17  
    18  func TestPidAlive(t *T.T) {
    19  	t.Run("pid-1", func(t *T.T) {
    20  		if runtime.GOOS != "windows" {
    21  			assert.True(t, pidAlive(1))
    22  		}
    23  	})
    24  
    25  	t.Run("pid-not-exist", func(t *T.T) {
    26  		assert.False(t, pidAlive(-1))
    27  	})
    28  
    29  	t.Run("cur-pid", func(t *T.T) {
    30  		assert.True(t, pidAlive(os.Getpid()))
    31  	})
    32  }
    33  
    34  func TestLockUnlock(t *T.T) {
    35  	t.Run("lock", func(t *T.T) {
    36  		p := t.TempDir()
    37  
    38  		wg := sync.WaitGroup{}
    39  
    40  		wg.Add(3)
    41  		go func() {
    42  			defer wg.Done()
    43  			fl := newFlock(p)
    44  
    45  			assert.NoError(t, fl.lock())
    46  			defer fl.unlock()
    47  
    48  			time.Sleep(time.Second * 5)
    49  		}()
    50  
    51  		time.Sleep(time.Second) // wait 1st goroutine ok
    52  
    53  		go func() {
    54  			defer wg.Done()
    55  			fl := newFlock(p)
    56  
    57  			err := fl.lock()
    58  			assert.Error(t, err)
    59  
    60  			t.Logf("[expect] err: %s", err.Error())
    61  		}()
    62  
    63  		time.Sleep(time.Second) // wait 2nd goroutine ok
    64  
    65  		go func() {
    66  			defer wg.Done()
    67  			fl := newFlock(p)
    68  
    69  			// try lock until ok
    70  			for {
    71  				if err := fl.lock(); err != nil {
    72  					t.Logf("[expect] err: %s", err.Error())
    73  					time.Sleep(time.Second)
    74  				} else {
    75  					break
    76  				}
    77  			}
    78  		}()
    79  
    80  		wg.Wait()
    81  	})
    82  }