github.com/jxskiss/gopkg@v0.17.3/forceexport/function_test.go (about) 1 package forceexport 2 3 import ( 4 "fmt" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func TestTimeNow(t *testing.T) { 11 var timeNowFunc func() (int64, int32) 12 assert.NotPanics(t, func() { 13 GetFunc(&timeNowFunc, "time.now") 14 }) 15 sec, nsec := timeNowFunc() 16 assert.Greater(t, sec, int64(0)) 17 assert.Greater(t, nsec, int32(0)) 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 assert.Equal(t, 4, addOne(3)) 30 31 var addOneFunc func(x int) int 32 assert.NotPanics(t, func() { 33 GetFunc(&addOneFunc, "github.com/jxskiss/gopkg/forceexport.addOne") 34 }) 35 assert.Equal(t, 4, addOneFunc(3)) 36 } 37 38 func TestGetSelf(t *testing.T) { 39 var getFunc func(interface{}, string) 40 assert.NotPanics(t, func() { 41 GetFunc(&getFunc, "github.com/jxskiss/gopkg/forceexport.GetFunc") 42 }) 43 44 _p := func(fn interface{}) string { return fmt.Sprintf("%p", fn) } 45 46 // The two functions should share the same code pointer, so they should 47 // have the same string representation. 48 assert.Equal(t, _p(getFunc), _p(GetFunc)) 49 50 // Call it again on itself! 51 assert.NotPanics(t, func() { 52 getFunc(&getFunc, "github.com/jxskiss/gopkg/forceexport.GetFunc") 53 }) 54 assert.Equal(t, _p(getFunc), _p(GetFunc)) 55 } 56 57 func TestInvalidFunc(t *testing.T) { 58 var invalidFunc func() 59 assert.Panics(t, func() { 60 GetFunc(&invalidFunc, "invalidpackage.invalidfunction") 61 }) 62 assert.Nil(t, invalidFunc) 63 }