github.com/uber/kraken@v0.1.4/utils/dedup/interval_trap_test.go (about)

     1  // Copyright (c) 2016-2019 Uber Technologies, Inc.
     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  package dedup_test
    15  
    16  import (
    17  	"sync"
    18  	"testing"
    19  	"time"
    20  
    21  	"github.com/uber/kraken/mocks/utils/dedup"
    22  	. "github.com/uber/kraken/utils/dedup"
    23  	"github.com/uber/kraken/utils/randutil"
    24  
    25  	"github.com/andres-erbsen/clock"
    26  	"github.com/golang/mock/gomock"
    27  )
    28  
    29  func TestIntervalTrap(t *testing.T) {
    30  	ctrl := gomock.NewController(t)
    31  	defer ctrl.Finish()
    32  
    33  	interval := time.Minute
    34  	clk := clock.NewMock()
    35  	clk.Set(time.Now())
    36  	task := mockdedup.NewMockIntervalTask(ctrl)
    37  
    38  	trap := NewIntervalTrap(interval, clk, task)
    39  
    40  	trap.Trap() // Noop.
    41  	trap.Trap() // Noop.
    42  
    43  	clk.Add(interval + 1)
    44  	task.EXPECT().Run()
    45  	trap.Trap()
    46  	trap.Trap() // Noop.
    47  
    48  	clk.Add(interval / 2)
    49  	trap.Trap() // Noop.
    50  
    51  	clk.Add(interval + 1)
    52  	task.EXPECT().Run()
    53  	trap.Trap()
    54  	trap.Trap() // Noop.
    55  }
    56  
    57  func TestIntervalTrapConcurrency(t *testing.T) {
    58  	ctrl := gomock.NewController(t)
    59  	defer ctrl.Finish()
    60  
    61  	task := mockdedup.NewMockIntervalTask(ctrl)
    62  
    63  	trap := NewIntervalTrap(100*time.Millisecond, clock.New(), task)
    64  
    65  	task.EXPECT().Run().Times(4)
    66  
    67  	var wg sync.WaitGroup
    68  	for i := 0; i < 50; i++ {
    69  		wg.Add(1)
    70  		go func() {
    71  			defer wg.Done()
    72  			for k := 0; k < 4; k++ {
    73  				// Guarantees that Trap() will be called exactly 4 times,
    74  				// as the interval between each Trap() call is >= 100ms
    75  				// for each goroutine and the total interval for a given
    76  				// goroutine will never reach 500ms.
    77  				time.Sleep(120*time.Millisecond +
    78  					randutil.Duration(10*time.Millisecond))
    79  				trap.Trap()
    80  			}
    81  		}()
    82  	}
    83  	wg.Wait()
    84  }