github.com/alangpierce/go-forceexport@v0.0.0-20160317203124-8f1d6941cd75/forceexport_test.go (about)

     1  package forceexport
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  )
     7  
     8  func TestTimeNow(t *testing.T) {
     9  	var timeNowFunc func() (int64, int32)
    10  	GetFunc(&timeNowFunc, "time.now")
    11  	sec, nsec := timeNowFunc()
    12  	if sec == 0 || nsec == 0 {
    13  		t.Error("Expected nonzero result from time.now().")
    14  	}
    15  }
    16  
    17  // Note that we need to disable inlining here, or else the function won't be
    18  // compiled into the binary. We also need to call it from the test so that the
    19  // compiler doesn't remove it because it's unused.
    20  //go:noinline
    21  func addOne(x int) int {
    22  	return x + 1
    23  }
    24  
    25  func TestAddOne(t *testing.T) {
    26  	if addOne(3) != 4 {
    27  		t.Error("addOne should work properly.")
    28  	}
    29  
    30  	var addOneFunc func(x int) int
    31  	err := GetFunc(&addOneFunc, "github.com/alangpierce/go-forceexport.addOne")
    32  	if err != nil {
    33  		t.Error("Expected nil error.")
    34  	}
    35  	if addOneFunc(3) != 4 {
    36  		t.Error("Expected addOneFunc to add one to 3.")
    37  	}
    38  }
    39  
    40  func TestGetSelf(t *testing.T) {
    41  	var getFunc func(interface{}, string) error
    42  	err := GetFunc(&getFunc, "github.com/alangpierce/go-forceexport.GetFunc")
    43  	if err != nil {
    44  		t.Error("Error: %s", err)
    45  	}
    46  	// The two functions should share the same code pointer, so they should
    47  	// have the same string representation.
    48  	if fmt.Sprint(getFunc) != fmt.Sprint(GetFunc) {
    49  		t.Errorf("Expected ")
    50  	}
    51  	// Call it again on itself!
    52  	err = getFunc(&getFunc, "github.com/alangpierce/go-forceexport.GetFunc")
    53  	if err != nil {
    54  		t.Error("Error: %s", err)
    55  	}
    56  	if fmt.Sprint(getFunc) != fmt.Sprint(GetFunc) {
    57  		t.Errorf("Expected ")
    58  	}
    59  }
    60  
    61  func TestInvalidFunc(t *testing.T) {
    62  	var invalidFunc func()
    63  	err := GetFunc(&invalidFunc, "invalidpackage.invalidfunction")
    64  	if err == nil {
    65  		t.Error("Expected an error.")
    66  	}
    67  	if invalidFunc != nil {
    68  		t.Error("Expected a nil function.")
    69  	}
    70  }