github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/util/caller/resolver_test.go (about)

     1  // Copyright 2015 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package caller
    12  
    13  import (
    14  	"fmt"
    15  	"path"
    16  	"regexp"
    17  	"testing"
    18  )
    19  
    20  func TestCallResolver(t *testing.T) {
    21  	cr := NewCallResolver(regexp.MustCompile(`resolver_test\.go.*$`))
    22  	// Also test that caching doesn't have obvious hiccups.
    23  	for i := 0; i < 2; i++ {
    24  		if l := len(cr.cache); l != i {
    25  			t.Fatalf("cache has %d entries, expected %d", l, i)
    26  		}
    27  		file, _, fun := func() (string, int, string) {
    28  			return cr.Lookup(1)
    29  		}()
    30  		if file != "resolver_test.go" {
    31  			t.Fatalf("wrong file '%s'", file)
    32  		}
    33  		if fun != "TestCallResolver" {
    34  			t.Fatalf("unexpected caller reported: %s", fun)
    35  		}
    36  	}
    37  }
    38  
    39  func TestDefaultCallResolver(t *testing.T) {
    40  	defer func() { defaultCallResolver.cache = map[uintptr]*cachedLookup{} }()
    41  
    42  	for i := 0; i < 2; i++ {
    43  		if l := len(defaultCallResolver.cache); l != i {
    44  			t.Fatalf("cache has %d entries, expected %d", l, i)
    45  		}
    46  		file, _, fun := Lookup(0)
    47  		if fun != "TestDefaultCallResolver" {
    48  			t.Fatalf("unexpected caller reported: %s", fun)
    49  		}
    50  
    51  		// NB: runtime.Caller always returns unix paths.
    52  		if expected := path.Join("util", "caller", "resolver_test.go"); file != expected {
    53  			t.Fatalf("expected '%s' got '%s'", expected, file)
    54  		}
    55  	}
    56  }
    57  
    58  func BenchmarkFormattedCaller(b *testing.B) {
    59  	for i := 0; i < b.N; i++ {
    60  		file, line, _ := Lookup(1)
    61  		s := fmt.Sprintf("%s:%d", file, line)
    62  		if testing.Verbose() {
    63  			b.Log(s)
    64  		}
    65  	}
    66  }
    67  
    68  func BenchmarkSimpleCaller(b *testing.B) {
    69  	for i := 0; i < b.N; i++ {
    70  		file, line, _ := Lookup(1)
    71  		if testing.Verbose() {
    72  			s := fmt.Sprintf("%s:%d", file, line)
    73  			b.Log(s)
    74  		}
    75  	}
    76  }