github.com/zeebo/goof@v0.0.0-20230907150950-e9457bc94477/troop_test.go (about)

     1  package goof
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  	"testing"
     8  )
     9  
    10  //go:noinline
    11  func Barf(err error) int {
    12  	if err != nil {
    13  		return len(err.Error())
    14  	}
    15  	return 5
    16  }
    17  
    18  // no dead code elim
    19  func init() { Barf(nil) }
    20  
    21  func (suite) TestCall(t *testing.T) {
    22  	symbol := fmt.Sprintf("%s.Barf", importPath)
    23  	if _, err := troop.Call(symbol, errors.New("hi")); err != nil {
    24  		t.Fatal(err)
    25  	}
    26  	if _, err := troop.Call(symbol, nil); err != nil {
    27  		t.Fatal(err)
    28  	}
    29  }
    30  
    31  func (suite) TestCallFprintf(t *testing.T) {
    32  	fmt.Fprintf(os.Stdout, "hello world %d\n", 2)
    33  	if _, err := troop.Call("fmt.Fprintf", os.Stdout, "hello world %d\n", []interface{}{2}); err != nil {
    34  		t.Fatal(err)
    35  	}
    36  }
    37  
    38  func (suite) TestCallFailures(t *testing.T) {
    39  	symbol := fmt.Sprintf("%s.Barf", importPath)
    40  	type is []interface{}
    41  
    42  	cases := []struct {
    43  		name string
    44  		args []interface{}
    45  	}{
    46  		{symbol, is{nil, nil}},   // too many args
    47  		{symbol, is{false}},      // wrong arg kind
    48  		{symbol, is{"hello", 2}}, // wrong arg kind
    49  	}
    50  
    51  	for i, c := range cases {
    52  		out, err := troop.Call(c.name, c.args...)
    53  		if err == nil {
    54  			t.Logf("%d: %+v", i, c)
    55  			t.Errorf("expected an error. out: %#v", out)
    56  		}
    57  	}
    58  }
    59  
    60  func (suite) TestGlobals(t *testing.T) {
    61  	troop_rv, err := troop.Global(fmt.Sprintf("%s.troop", importPath))
    62  	if err != nil {
    63  		t.Fatal(err)
    64  	}
    65  	troop2 := troop_rv.Addr().Interface().(*Troop)
    66  	if troop2 != &troop {
    67  		t.Fatal("got a different troop")
    68  	}
    69  }