github.com/erikdubbelboer/gopher-lua@v0.0.0-20160512044044-e68f0dc85040/testutils_test.go (about)

     1  package lua
     2  
     3  import (
     4  	"fmt"
     5  	"path/filepath"
     6  	"regexp"
     7  	"runtime"
     8  	"testing"
     9  )
    10  
    11  func positionString(level int) string {
    12  	_, file, line, _ := runtime.Caller(level + 1)
    13  	return fmt.Sprintf("%v:%v:", filepath.Base(file), line)
    14  }
    15  
    16  func errorIfNotEqual(t *testing.T, v1, v2 interface{}) {
    17  	if v1 != v2 {
    18  		t.Errorf("%v '%v' expected, but got '%v'", positionString(1), v1, v2)
    19  	}
    20  }
    21  
    22  func errorIfFalse(t *testing.T, cond bool, msg string, args ...interface{}) {
    23  	if !cond {
    24  		if len(args) > 0 {
    25  			t.Errorf("%v %v", positionString(1), fmt.Sprintf(msg, args...))
    26  		} else {
    27  			t.Errorf("%v %v", positionString(1), msg)
    28  		}
    29  	}
    30  }
    31  
    32  func errorIfNotNil(t *testing.T, v1 interface{}) {
    33  	if fmt.Sprint(v1) != "<nil>" {
    34  		t.Errorf("%v nil expected, but got '%v'", positionString(1), v1)
    35  	}
    36  }
    37  
    38  func errorIfNil(t *testing.T, v1 interface{}) {
    39  	if fmt.Sprint(v1) == "<nil>" {
    40  		t.Errorf("%v non-nil value expected, but got nil", positionString(1))
    41  	}
    42  }
    43  
    44  func errorIfScriptFail(t *testing.T, L *LState, script string) {
    45  	if err := L.DoString(script); err != nil {
    46  		t.Errorf("%v %v", positionString(1), err.Error())
    47  	}
    48  }
    49  
    50  func errorIfGFuncFail(t *testing.T, L *LState, f LGFunction) {
    51  	if err := L.GPCall(f, LNil); err != nil {
    52  		t.Errorf("%v %v", positionString(1), err.Error())
    53  	}
    54  }
    55  
    56  func errorIfScriptNotFail(t *testing.T, L *LState, script string, pattern string) {
    57  	if err := L.DoString(script); err != nil {
    58  		reg := regexp.MustCompile(pattern)
    59  		if len(reg.FindStringIndex(err.Error())) == 0 {
    60  			t.Errorf("%v error message '%v' does not contains given pattern string '%v'.", positionString(1), err.Error(), pattern)
    61  			return
    62  		}
    63  		return
    64  	}
    65  	t.Errorf("%v script should fail", positionString(1))
    66  }
    67  
    68  func errorIfGFuncNotFail(t *testing.T, L *LState, f LGFunction, pattern string) {
    69  	if err := L.GPCall(f, LNil); err != nil {
    70  		reg := regexp.MustCompile(pattern)
    71  		if len(reg.FindStringIndex(err.Error())) == 0 {
    72  			t.Errorf("%v error message '%v' does not contains given pattern string '%v'.", positionString(1), err.Error(), pattern)
    73  			return
    74  		}
    75  		return
    76  	}
    77  	t.Errorf("%v LGFunction should fail", positionString(1))
    78  }