github.com/lsg2020/go-forceexport@v1.0.5/forceexport_test.go (about)

     1  package forceexport
     2  
     3  import (
     4  	"reflect"
     5  	"runtime"
     6  	"testing"
     7  )
     8  
     9  func FuncName(f interface{}) string {
    10  	return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
    11  }
    12  
    13  func aTestTimeNow(t *testing.T) {
    14  	var timeNowFunc func() (int64, int32)
    15  	_ = GetFunc(&timeNowFunc, "time.now")
    16  	sec, nsec := timeNowFunc()
    17  	if sec == 0 || nsec == 0 {
    18  		t.Error("Expected nonzero result from time.now().")
    19  	}
    20  }
    21  
    22  // Note that we need to disable inlining here, or else the function won't be
    23  // compiled into the binary. We also need to call it from the test so that the
    24  // compiler doesn't remove it because it's unused.
    25  //go:noinline
    26  func addOne(x int) int {
    27  	return x + 1
    28  }
    29  
    30  func aTestAddOne(t *testing.T) {
    31  	if addOne(3) != 4 {
    32  		t.Error("addOne should work properly.")
    33  	}
    34  
    35  	var addOneFunc func(x int) int
    36  	err := GetFunc(&addOneFunc, "github.com/lsg2020/go-forceexport.addOne")
    37  	if err != nil {
    38  		t.Error("Expected nil error.")
    39  	}
    40  	if addOneFunc(3) != 4 {
    41  		t.Error("Expected addOneFunc to add one to 3.")
    42  	}
    43  }
    44  
    45  func aTestGetSelf(t *testing.T) {
    46  	var getFunc func(interface{}, string) error
    47  	err := GetFunc(&getFunc, "github.com/lsg2020/go-forceexport.GetFunc")
    48  	if err != nil {
    49  		t.Errorf("Error: %s", err)
    50  	}
    51  	// The two functions should share the same code pointer, so they should
    52  	// have the same string representation.
    53  	if FuncName(getFunc) != FuncName(GetFunc) {
    54  		t.Errorf("Expected ")
    55  	}
    56  	// Call it again on itself!
    57  	err = getFunc(&getFunc, "github.com/lsg2020/go-forceexport.GetFunc")
    58  	if err != nil {
    59  		t.Errorf("Error: %s", err)
    60  	}
    61  	if FuncName(getFunc) != FuncName(GetFunc) {
    62  		t.Errorf("Expected ")
    63  	}
    64  }
    65  
    66  func TestInvalidFunc(t *testing.T) {
    67  	var invalidFunc func()
    68  	err := GetFunc(&invalidFunc, "invalidpackage.invalidfunction")
    69  	if err == nil {
    70  		t.Error("Expected an error.")
    71  	}
    72  	if invalidFunc != nil {
    73  		t.Error("Expected a nil function.")
    74  	}
    75  }
    76  
    77  // BenchmarkGetMain check how long it takes to find the symbol main.main,
    78  // which is typically the last func symbol(by experiment).
    79  func BenchmarkGetMain(b *testing.B) {
    80  	for i := 0; i < b.N; i++ {
    81  		var main_init func()
    82  		_ = GetFunc(&main_init, "main.main")
    83  	}
    84  }