eval_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package R
  2. import (
  3. //"log"
  4. "math"
  5. "testing"
  6. "github.com/stretchrcom/testify/assert"
  7. )
  8. func TestEvalBadExpr(t *testing.T) {
  9. assert.Equal(t, 1, Init())
  10. r, err := Eval("x+")
  11. assert.Nil(t, r)
  12. assert.Error(t, err)
  13. assert.Panics(t, func() {
  14. EvalOrDie("+1*(")
  15. })
  16. }
  17. func TestEval(t *testing.T) {
  18. assert.Equal(t, 1, Init())
  19. r, err := Eval("1+3*4")
  20. assert.Nil(t, err)
  21. assert.True(t, r.IsNumeric())
  22. assert.False(t, r.IsComplex())
  23. assert.Panics(t, func() { r.AsComplex() })
  24. num := r.AsNumeric()
  25. assert.Equal(t, 1, num.Len())
  26. assert.Equal(t, 13, num.Get(0))
  27. r = EvalOrDie("sqrt(-2+0i)")
  28. assert.False(t, r.IsNumeric())
  29. assert.True(t, r.IsComplex())
  30. assert.Panics(t, func() { r.AsNumeric() })
  31. cpl := r.AsComplex()
  32. assert.Equal(t, 1, cpl.Len())
  33. assert.Equal(t, complex(0, math.Sqrt(2)), cpl.Get(0))
  34. }
  35. func TestEvalWithVariables(t *testing.T) {
  36. x := NewNumericVector([]float64{10, 13, -15})
  37. SetSymbol("x", x)
  38. r := EvalOrDie("sum(x)")
  39. assert.Equal(t, 8, r.AsNumeric().Get(0))
  40. }
  41. func TestScriptFFT(t *testing.T) {
  42. assert.Equal(t, 1, Init())
  43. EvalOrDie("library(stats)")
  44. data := []float64{1, 2, 3, 4, 5, 6, 7, 8}
  45. v := NewNumericVector(data)
  46. SetSymbol("y", v)
  47. r, err := Eval("fft(y, inverse=FALSE)")
  48. assert.True(t, r.IsComplex())
  49. assert.Nil(t, err)
  50. z := r.AsComplex()
  51. assert.Equal(t, 8, z.Len())
  52. assert.Equal(t, complex(36, 0), z.Get(0))
  53. }
  54. func TestMkTrend(t *testing.T) {
  55. assert.Equal(t, 1, Init())
  56. Eval("library(stats)")
  57. Eval("library(chron)")
  58. Eval("library(fume)")
  59. data := []float64{1, 2, 3, 4, 5, 6, 7, 8}
  60. v := NewNumericVector(data)
  61. SetSymbol("a1", v)
  62. r, err := Eval("mkTrend(a1)")
  63. //r, err := Eval("mkTrend(a1)")
  64. assert.True(t, r.IsGenericVector())
  65. assert.Nil(t, err)
  66. //z := r.AsComplex()
  67. //assert.Equal(t, 8, z.Len())
  68. //assert.Equal(t, complex(36, 0), z.Get(0))
  69. }