evaluator_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package evaluator
  2. import (
  3. "github/runnignwater/monkey/lexer"
  4. "github/runnignwater/monkey/object"
  5. "github/runnignwater/monkey/parser"
  6. "testing"
  7. )
  8. func TestEvalIntegerExpression(t *testing.T) {
  9. tests := []struct {
  10. input string
  11. expected int64
  12. }{
  13. {"5", 5},
  14. {"10", 10},
  15. {"-5", -5},
  16. {"-10", -10},
  17. {"5+5+5+5-10", 10},
  18. {"2*2*2*2*2", 32},
  19. {"-50+100+-50", 0},
  20. }
  21. for _, tt := range tests {
  22. evaluated := testEval(tt.input)
  23. testIntegerObject(t, evaluated, tt.expected)
  24. }
  25. }
  26. func TestEvalBooleanExpression(t *testing.T) {
  27. tests := []struct {
  28. input string
  29. expected bool
  30. }{
  31. {"true", true},
  32. {"false", false},
  33. {"1 < 2", true},
  34. {"1 > 2", false},
  35. {"1 == 1", true},
  36. {"1 != 1", false},
  37. {"1 == 2", false},
  38. {"1 != 2", true},
  39. {"true == true", true},
  40. {"false == false", true},
  41. {"(1 < 2) == true", true},
  42. }
  43. for _, tt := range tests {
  44. evaluated := testEval(tt.input)
  45. testBooleanObject(t, evaluated, tt.expected)
  46. }
  47. }
  48. func TestBangOperator(t *testing.T) {
  49. tests := []struct {
  50. input string
  51. expected bool
  52. }{
  53. {"!true", false},
  54. {"!false", true},
  55. {"!5", false},
  56. {"!!true", true},
  57. {"!!false", false},
  58. {"!!5", true},
  59. }
  60. for _, tt := range tests {
  61. evaluated := testEval(tt.input)
  62. testBooleanObject(t, evaluated, tt.expected)
  63. }
  64. }
  65. func testIntegerObject(t *testing.T, obj object.Object, expected int64) bool {
  66. result, ok := obj.(*object.Integer)
  67. if !ok {
  68. t.Errorf("object is not Integer. got=%T (%+v)", obj, obj)
  69. return false
  70. }
  71. if result.Value != expected {
  72. t.Errorf("object has wrong value. got=%d, want=%d", result.Value, expected)
  73. return false
  74. }
  75. return true
  76. }
  77. func testBooleanObject(t *testing.T, obj object.Object, expected bool) bool {
  78. result, ok := obj.(*object.Boolean)
  79. if !ok {
  80. t.Errorf("object is not Boolean. got=%T (%+v)", obj, obj)
  81. return false
  82. }
  83. if result.Value != expected {
  84. t.Errorf("object has wrong value. got=%t, want=%t", result.Value, expected)
  85. return false
  86. }
  87. return true
  88. }
  89. func testEval(input string) object.Object {
  90. l := lexer.New(input)
  91. p := parser.New(l)
  92. program := p.ParseProgram()
  93. return Eval(program)
  94. }