...

Source file src/github.com/google/certificate-transparency-go/schedule/schedule_test.go

Documentation: github.com/google/certificate-transparency-go/schedule

     1  // Copyright 2019 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 schedule
    16  
    17  import (
    18  	"context"
    19  	"sync/atomic"
    20  	"testing"
    21  	"time"
    22  )
    23  
    24  func TestEvery(t *testing.T) {
    25  	for _, test := range []struct {
    26  		name           string
    27  		period         time.Duration
    28  		timeout        time.Duration
    29  		wantExecutions uint32
    30  	}{
    31  		{
    32  			name:           "0 runs",
    33  			period:         100 * time.Millisecond,
    34  			timeout:        0,
    35  			wantExecutions: 0,
    36  		},
    37  		{
    38  			name:           "1 run",
    39  			period:         100 * time.Millisecond,
    40  			timeout:        50 * time.Millisecond,
    41  			wantExecutions: 1,
    42  		},
    43  		{
    44  			name:           "3 runs 100ms apart",
    45  			period:         100 * time.Millisecond,
    46  			timeout:        250 * time.Millisecond,
    47  			wantExecutions: 3,
    48  		},
    49  	} {
    50  		t.Run(test.name, func(t *testing.T) {
    51  			test := test
    52  			t.Parallel()
    53  			ctx, cancel := context.WithTimeout(context.Background(), test.timeout)
    54  			defer cancel()
    55  			var counter uint32
    56  
    57  			Every(ctx, test.period, func(ctx context.Context) {
    58  				atomic.AddUint32(&counter, 1)
    59  			})
    60  
    61  			if got, want := atomic.LoadUint32(&counter), test.wantExecutions; got != want {
    62  				t.Fatalf("Every(%v, f): executed f %d times, want %d times", test.period, got, want)
    63  			}
    64  		})
    65  	}
    66  }
    67  

View as plain text