vitess.io/vitess@v0.16.2/go/sync2/semaphore_test.go (about)

     1  /*
     2  Copyright 2019 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package sync2
    18  
    19  import (
    20  	"context"
    21  	"testing"
    22  	"time"
    23  
    24  	"github.com/stretchr/testify/assert"
    25  )
    26  
    27  func TestSemaNoTimeout(t *testing.T) {
    28  	s := NewSemaphore(1, 0)
    29  	s.Acquire()
    30  	released := false
    31  	go func() {
    32  		released = true
    33  		s.Release()
    34  	}()
    35  	s.Acquire()
    36  	assert.True(t, released)
    37  }
    38  
    39  func TestSemaTimeout(t *testing.T) {
    40  	s := NewSemaphore(1, 1*time.Millisecond)
    41  	s.Acquire()
    42  	release := make(chan struct{})
    43  	released := make(chan struct{})
    44  	go func() {
    45  		<-release
    46  		s.Release()
    47  		released <- struct{}{}
    48  	}()
    49  	assert.False(t, s.Acquire())
    50  	release <- struct{}{}
    51  	<-released
    52  	assert.True(t, s.Acquire())
    53  }
    54  
    55  func TestSemaAcquireContext(t *testing.T) {
    56  	s := NewSemaphore(1, 0)
    57  	s.Acquire()
    58  	release := make(chan struct{})
    59  	released := make(chan struct{})
    60  	go func() {
    61  		<-release
    62  		s.Release()
    63  		released <- struct{}{}
    64  	}()
    65  	ctx, cancel := context.WithCancel(context.Background())
    66  	cancel()
    67  	assert.False(t, s.AcquireContext(ctx))
    68  	release <- struct{}{}
    69  	<-released
    70  	assert.True(t, s.AcquireContext(context.Background()))
    71  }
    72  
    73  func TestSemaTryAcquire(t *testing.T) {
    74  	s := NewSemaphore(1, 0)
    75  	assert.True(t, s.TryAcquire())
    76  	assert.False(t, s.TryAcquire())
    77  	s.Release()
    78  	assert.True(t, s.TryAcquire())
    79  }