ipn: tag and test for grinder log lines (#711)

Signed-off-by: Wendi <wendi.yu@yahoo.ca>
This commit is contained in:
Wendi Yu
2020-08-25 12:42:54 -06:00
committed by GitHub
parent cd7bc02ab1
commit a3fb422a39
4 changed files with 204 additions and 0 deletions
+48
View File
@@ -7,7 +7,10 @@ package tstest
import (
"log"
"os"
"sync"
"testing"
"tailscale.com/types/logger"
)
type testLogWriter struct {
@@ -41,3 +44,48 @@ func (panicLogWriter) Write(b []byte) (int, error) {
func PanicOnLog() {
log.SetOutput(panicLogWriter{})
}
// ListenFor produces a LogListener wrapping a given logf with the given logStrings
func ListenFor(logf logger.Logf, logStrings []string) *LogListener {
ret := LogListener{
logf: logf,
listenFor: logStrings,
seen: make(map[string]bool),
}
for _, line := range logStrings {
ret.seen[line] = false
}
return &ret
}
// LogListener takes a list of log lines to listen for
type LogListener struct {
logf logger.Logf
listenFor []string
mu sync.Mutex
seen map[string]bool
}
// Logf records and logs a given line
func (ll *LogListener) Logf(format string, args ...interface{}) {
ll.mu.Lock()
if _, ok := ll.seen[format]; ok {
ll.seen[format] = true
}
ll.mu.Unlock()
ll.logf(format, args)
}
// Check returns which lines haven't been logged yet
func (ll *LogListener) Check() []string {
ll.mu.Lock()
defer ll.mu.Unlock()
var notSeen []string
for _, line := range ll.listenFor {
if !ll.seen[line] {
notSeen = append(notSeen, line)
}
}
return notSeen
}
+46
View File
@@ -0,0 +1,46 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tstest
import "testing"
func TestLogListener(t *testing.T) {
var (
l1 = "line 1: %s"
l2 = "line 2: %s"
l3 = "line 3: %s"
lineList = []string{l1, l2}
)
ll := ListenFor(t.Logf, lineList)
if len(ll.Check()) != len(lineList) {
t.Errorf("expected %v, got %v", lineList, ll.Check())
}
ll.Logf(l3, "hi")
if len(ll.Check()) != len(lineList) {
t.Errorf("expected %v, got %v", lineList, ll.Check())
}
ll.Logf(l1, "hi")
if len(ll.Check()) != len(lineList)-1 {
t.Errorf("expected %v, got %v", lineList, ll.Check())
}
ll.Logf(l1, "bye")
if len(ll.Check()) != len(lineList)-1 {
t.Errorf("expected %v, got %v", lineList, ll.Check())
}
ll.Logf(l2, "hi")
if ll.Check() != nil {
t.Errorf("expected empty list, got ll.Check()")
}
}