github.com/szmcdull/go-forceexport@v0.0.0-20230908151957-3dac42f564da/forceexport_test.go (about)

     1  package forceexport
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  )
     7  
     8  func TestTimeNow(t *testing.T) {
     9  	var timeNowFunc func() (int64, int32)
    10  	GetFunc(&timeNowFunc, "time.now")
    11  	if timeNowFunc == nil {
    12  		GetFunc(&timeNowFunc, "runtime.now")
    13  	}
    14  	sec, nsec := timeNowFunc()
    15  	if sec == 0 || nsec == 0 {
    16  		t.Error("Expected nonzero result from time.now().")
    17  	}
    18  }
    19  
    20  // Note that we need to disable inlining here, or else the function won't be
    21  // compiled into the binary. We also need to call it from the test so that the
    22  // compiler doesn't remove it because it's unused.
    23  //go:noinline
    24  func addOne(x int) int {
    25  	return x + 1
    26  }
    27  
    28  func TestAddOne(t *testing.T) {
    29  	if addOne(3) != 4 {
    30  		t.Error("addOne should work properly.")
    31  	}
    32  
    33  	var addOneFunc func(x int) int
    34  	err := GetFunc(&addOneFunc, "github.com/szmcdull/go-forceexport.addOne")
    35  	if err != nil {
    36  		t.Error("Expected nil error.")
    37  	}
    38  	if addOneFunc(3) != 4 {
    39  		t.Error("Expected addOneFunc to add one to 3.")
    40  	}
    41  }
    42  
    43  func GetPointer(v interface{}) uintptr {
    44  	val := reflect.ValueOf(v)
    45  	return val.Pointer()
    46  }
    47  
    48  func TestFunc1(t *testing.T) {
    49  }
    50  
    51  func TestFunc2(t *testing.T) {
    52  }
    53  
    54  func TestFunc3(t *testing.T) {
    55  }
    56  
    57  func TestFunc4(t *testing.T) {
    58  }
    59  
    60  func TestInvalidFunc(t *testing.T) {
    61  	var invalidFunc func()
    62  	err := GetFunc(&invalidFunc, "invalidpackage.invalidfunction")
    63  	if err == nil {
    64  		t.Error("Expected an error.")
    65  	}
    66  	if invalidFunc != nil {
    67  		t.Error("Expected a nil function.")
    68  	}
    69  }
    70  
    71  func TestForceExport(t *testing.T) {
    72  	var func1, func2, func3, func4 func(*testing.T)
    73  	_ = GetFunc(&func1, `github.com/szmcdull/go-forceexport.TestFunc1`)
    74  	_ = GetFunc(&func2, `github.com/szmcdull/go-forceexport.TestFunc2`)
    75  	_ = GetFunc(&func3, `github.com/szmcdull/go-forceexport.TestFunc3`)
    76  	_ = GetFunc(&func4, `github.com/szmcdull/go-forceexport.TestFunc4`)
    77  	if func1 == nil || func2 == nil || func3 == nil || func4 == nil {
    78  		t.Error(`func == nil`)
    79  	} else {
    80  		// r1 := func1()
    81  		// r2 := func2()
    82  		// r3 := func3()
    83  		// r4 := func4()
    84  		// if r1 != 1 || r2 != 2 || r3 != 3 || r4 != 4 {
    85  		// 	t.Error(`result wrong`)
    86  		// }
    87  	}
    88  }