testutils_test.go 2.1 KB

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