golang.org/x/tools/gopls@v0.15.3/internal/server/prompt_test.go (about)

     1  // Copyright 2023 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package server
     6  
     7  import (
     8  	"path/filepath"
     9  	"sync"
    10  	"sync/atomic"
    11  	"testing"
    12  )
    13  
    14  func TestAcquireFileLock(t *testing.T) {
    15  	name := filepath.Join(t.TempDir(), "config.json")
    16  
    17  	const concurrency = 100
    18  	var acquired int32
    19  	var releasers [concurrency]func()
    20  	defer func() {
    21  		for _, r := range releasers {
    22  			if r != nil {
    23  				r()
    24  			}
    25  		}
    26  	}()
    27  
    28  	var wg sync.WaitGroup
    29  	for i := range releasers {
    30  		i := i
    31  		wg.Add(1)
    32  		go func() {
    33  			defer wg.Done()
    34  
    35  			release, ok, err := acquireLockFile(name)
    36  			if err != nil {
    37  				t.Errorf("Acquire failed: %v", err)
    38  				return
    39  			}
    40  			if ok {
    41  				atomic.AddInt32(&acquired, 1)
    42  				releasers[i] = release
    43  			}
    44  		}()
    45  	}
    46  
    47  	wg.Wait()
    48  
    49  	if acquired != 1 {
    50  		t.Errorf("Acquire succeeded %d times, expected exactly 1", acquired)
    51  	}
    52  }
    53  
    54  func TestReleaseAndAcquireFileLock(t *testing.T) {
    55  	name := filepath.Join(t.TempDir(), "config.json")
    56  
    57  	acquire := func() (func(), bool) {
    58  		t.Helper()
    59  		release, ok, err := acquireLockFile(name)
    60  		if err != nil {
    61  			t.Fatal(err)
    62  		}
    63  		return release, ok
    64  	}
    65  
    66  	release, ok := acquire()
    67  	if !ok {
    68  		t.Fatal("failed to Acquire")
    69  	}
    70  	if release2, ok := acquire(); ok {
    71  		release()
    72  		release2()
    73  		t.Fatalf("Acquire succeeded unexpectedly")
    74  	}
    75  
    76  	release()
    77  	release3, ok := acquire()
    78  	release3()
    79  	if !ok {
    80  		t.Fatalf("failed to Acquire")
    81  	}
    82  }