2019-01-31 08:50:15 +03:00
|
|
|
package script_test
|
|
|
|
|
|
|
|
import (
|
2019-03-04 21:21:39 +03:00
|
|
|
"strings"
|
2019-01-31 08:50:15 +03:00
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/d5/tengo/assert"
|
2019-03-04 21:21:39 +03:00
|
|
|
"github.com/d5/tengo/objects"
|
2019-01-31 08:50:15 +03:00
|
|
|
"github.com/d5/tengo/script"
|
|
|
|
)
|
|
|
|
|
2019-03-18 18:15:26 +03:00
|
|
|
func TestScriptSourceModule(t *testing.T) {
|
2019-01-31 08:50:15 +03:00
|
|
|
// script1 imports "mod1"
|
2019-02-02 10:27:29 +03:00
|
|
|
scr := script.New([]byte(`out := import("mod")`))
|
2019-03-20 11:28:40 +03:00
|
|
|
mods := objects.NewModuleMap()
|
|
|
|
mods.AddSourceModule("mod", []byte(`export 5`))
|
|
|
|
scr.SetImports(mods)
|
2019-02-02 10:27:29 +03:00
|
|
|
c, err := scr.Run()
|
2019-03-20 11:28:40 +03:00
|
|
|
if !assert.NoError(t, err) {
|
|
|
|
return
|
|
|
|
}
|
2019-01-31 08:50:15 +03:00
|
|
|
assert.Equal(t, int64(5), c.Get("out").Value())
|
|
|
|
|
2019-02-02 10:27:29 +03:00
|
|
|
// executing module function
|
|
|
|
scr = script.New([]byte(`fn := import("mod"); out := fn()`))
|
2019-03-20 11:28:40 +03:00
|
|
|
mods = objects.NewModuleMap()
|
|
|
|
mods.AddSourceModule("mod", []byte(`a := 3; export func() { return a + 5 }`))
|
|
|
|
scr.SetImports(mods)
|
2019-02-02 10:27:29 +03:00
|
|
|
c, err = scr.Run()
|
2019-03-20 11:28:40 +03:00
|
|
|
if !assert.NoError(t, err) {
|
|
|
|
return
|
|
|
|
}
|
2019-02-02 10:27:29 +03:00
|
|
|
assert.Equal(t, int64(8), c.Get("out").Value())
|
2019-01-31 08:50:15 +03:00
|
|
|
|
2019-02-02 10:27:29 +03:00
|
|
|
scr = script.New([]byte(`out := import("mod")`))
|
2019-03-20 11:28:40 +03:00
|
|
|
mods = objects.NewModuleMap()
|
|
|
|
mods.AddSourceModule("mod", []byte(`text := import("text"); export text.title("foo")`))
|
|
|
|
mods.AddBuiltinModule("text", map[string]objects.Object{
|
|
|
|
"title": &objects.UserFunction{Name: "title", Value: func(args ...objects.Object) (ret objects.Object, err error) {
|
|
|
|
s, _ := objects.ToString(args[0])
|
|
|
|
return &objects.String{Value: strings.Title(s)}, nil
|
|
|
|
}},
|
2019-02-02 10:27:29 +03:00
|
|
|
})
|
2019-03-20 11:28:40 +03:00
|
|
|
scr.SetImports(mods)
|
2019-02-02 10:27:29 +03:00
|
|
|
c, err = scr.Run()
|
2019-03-20 11:28:40 +03:00
|
|
|
if !assert.NoError(t, err) {
|
|
|
|
return
|
|
|
|
}
|
2019-02-02 10:27:29 +03:00
|
|
|
assert.Equal(t, "Foo", c.Get("out").Value())
|
2019-03-18 18:15:26 +03:00
|
|
|
scr.SetImports(nil)
|
2019-02-02 10:27:29 +03:00
|
|
|
_, err = scr.Run()
|
2019-03-20 11:28:40 +03:00
|
|
|
if !assert.Error(t, err) {
|
|
|
|
return
|
|
|
|
}
|
2019-01-31 08:50:15 +03:00
|
|
|
}
|