vitess.io/vitess@v0.16.2/go/vt/logutil/throttled_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 logutil 18 19 import ( 20 "fmt" 21 "testing" 22 "time" 23 ) 24 25 func skippedCount(tl *ThrottledLogger) int { 26 tl.mu.Lock() 27 defer tl.mu.Unlock() 28 return tl.skippedCount 29 } 30 31 func TestThrottledLogger(t *testing.T) { 32 // Install a fake log func for testing. 33 log := make(chan string) 34 infoDepth = func(depth int, args ...any) { 35 log <- fmt.Sprint(args...) 36 } 37 interval := 100 * time.Millisecond 38 tl := NewThrottledLogger("name", interval) 39 40 start := time.Now() 41 42 go tl.Infof("test %v", 1) 43 if got, want := <-log, "name: test 1"; got != want { 44 t.Errorf("got %q, want %q", got, want) 45 } 46 47 go tl.Infof("test %v", 2) 48 if got, want := <-log, "name: skipped 1 log messages"; got != want { 49 t.Errorf("got %q, want %q", got, want) 50 } 51 if got, want := skippedCount(tl), 0; got != want { 52 t.Errorf("skippedCount is %v but was expecting %v after waiting", got, want) 53 } 54 if got := time.Since(start); got < interval { 55 t.Errorf("didn't wait long enough before logging, got %v, want >= %v", got, interval) 56 } 57 58 go tl.Infof("test %v", 3) 59 if got, want := <-log, "name: test 3"; got != want { 60 t.Errorf("got %q, want %q", got, want) 61 } 62 if got, want := skippedCount(tl), 0; got != want { 63 t.Errorf("skippedCount is %v but was expecting %v", got, want) 64 } 65 }