Use Object.Copy when cloning globals in Compiled (#393)

This commit is contained in:
I Putu Susila 2022-09-25 21:30:50 +07:00 committed by GitHub
parent 8a3f5bdb11
commit dfcfd6661c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 1 deletions

View file

@ -259,7 +259,7 @@ func (c *Compiled) Clone() *Compiled {
// copy global objects
for idx, g := range c.globals {
if g != nil {
clone.globals[idx] = g
clone.globals[idx] = g.Copy()
}
}
return clone

View file

@ -640,3 +640,28 @@ func compiledIsDefined(
) {
require.Equal(t, expected, c.IsDefined(name))
}
func TestCompiled_Clone(t *testing.T) {
script := tengo.NewScript([]byte(`
count += 1
data["b"] = 2
`))
err := script.Add("data", map[string]interface{}{"a": 1})
require.NoError(t, err)
err = script.Add("count", 1000)
require.NoError(t, err)
compiled, err := script.Compile()
require.NoError(t, err)
clone := compiled.Clone()
err = clone.RunContext(context.Background())
require.NoError(t, err)
require.Equal(t, 1000, compiled.Get("count").Int())
require.Equal(t, 1, len(compiled.Get("data").Map()))
require.Equal(t, 1001, clone.Get("count").Int())
require.Equal(t, 2, len(clone.Get("data").Map()))
}