agones.dev/agones@v1.54.0/pkg/util/fswatch/fswatch_test.go (about)

     1  // Copyright 2022 Google LLC All Rights Reserved.
     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 fswatch
    16  
    17  import (
    18  	"errors"
    19  	"testing"
    20  	"time"
    21  
    22  	"github.com/stretchr/testify/assert"
    23  	"gopkg.in/fsnotify.v1"
    24  )
    25  
    26  func TestBatchWatch(t *testing.T) {
    27  	eventChan := make(chan fsnotify.Event)
    28  	errorChan := make(chan error)
    29  	cancelChan := make(chan struct{})
    30  	defer close(cancelChan)
    31  
    32  	eventOut := make(chan struct{}, 1) // only allow one event
    33  	errorCount := 0
    34  
    35  	go batchWatch(time.Second, eventChan, errorChan, cancelChan, func() {
    36  		select {
    37  		case eventOut <- struct{}{}:
    38  			// capacity
    39  		default:
    40  			assert.FailNow(t, "second event written - did not want")
    41  		}
    42  	}, func(error) {
    43  		errorCount++
    44  	})
    45  
    46  	drainEventAndErrors := func(wantErrors int) {
    47  		timeout := time.NewTimer(2 * time.Second)
    48  		select {
    49  		case <-eventOut:
    50  		case <-timeout.C:
    51  			assert.FailNow(t, "no event in 2s")
    52  		}
    53  		assert.Equal(t, wantErrors, errorCount)
    54  	}
    55  
    56  	for i := 0; i < 10; i++ {
    57  		eventChan <- fsnotify.Event{}
    58  	}
    59  	drainEventAndErrors(0)
    60  
    61  	for i := 0; i < 10; i++ {
    62  		errorChan <- errors.New("some error")
    63  		eventChan <- fsnotify.Event{}
    64  	}
    65  	drainEventAndErrors(10)
    66  }