From dfcfd6661ca87cfc590b041bb7f7421134f0e4f8 Mon Sep 17 00:00:00 2001 From: I Putu Susila Date: Sun, 25 Sep 2022 21:30:50 +0700 Subject: [PATCH] Use Object.Copy when cloning globals in Compiled (#393) --- script.go | 2 +- script_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/script.go b/script.go index 82b02f5..4cca4d0 100644 --- a/script.go +++ b/script.go @@ -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 diff --git a/script_test.go b/script_test.go index 9ab2015..a84941c 100644 --- a/script_test.go +++ b/script_test.go @@ -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())) +}