go.starlark.net@v0.0.0-20231101134539-556fd59b42f6/internal/compile/compile_test.go (about) 1 package compile_test 2 3 import ( 4 "bytes" 5 "strings" 6 "testing" 7 8 "go.starlark.net/starlark" 9 ) 10 11 // TestSerialization verifies that a serialized program can be loaded, 12 // deserialized, and executed. 13 func TestSerialization(t *testing.T) { 14 predeclared := starlark.StringDict{ 15 "x": starlark.String("mur"), 16 "n": starlark.MakeInt(2), 17 } 18 const src = ` 19 def mul(a, b): 20 return a * b 21 22 y = mul(x, n) 23 ` 24 _, oldProg, err := starlark.SourceProgram("mul.star", src, predeclared.Has) 25 if err != nil { 26 t.Fatal(err) 27 } 28 29 buf := new(bytes.Buffer) 30 if err := oldProg.Write(buf); err != nil { 31 t.Fatalf("oldProg.WriteTo: %v", err) 32 } 33 34 newProg, err := starlark.CompiledProgram(buf) 35 if err != nil { 36 t.Fatalf("CompiledProgram: %v", err) 37 } 38 39 thread := new(starlark.Thread) 40 globals, err := newProg.Init(thread, predeclared) 41 if err != nil { 42 t.Fatalf("newProg.Init: %v", err) 43 } 44 if got, want := globals["y"], starlark.String("murmur"); got != want { 45 t.Errorf("Value of global was %s, want %s", got, want) 46 t.Logf("globals: %v", globals) 47 } 48 49 // Verify stack frame. 50 predeclared["n"] = starlark.None 51 _, err = newProg.Init(thread, predeclared) 52 evalErr, ok := err.(*starlark.EvalError) 53 if !ok { 54 t.Fatalf("newProg.Init call returned err %v, want *EvalError", err) 55 } 56 const want = `Traceback (most recent call last): 57 mul.star:5:8: in <toplevel> 58 mul.star:3:14: in mul 59 Error: unknown binary op: string * NoneType` 60 if got := evalErr.Backtrace(); got != want { 61 t.Fatalf("got <<%s>>, want <<%s>>", got, want) 62 } 63 } 64 65 func TestGarbage(t *testing.T) { 66 const garbage = "This is not a compiled Starlark program." 67 _, err := starlark.CompiledProgram(strings.NewReader(garbage)) 68 if err == nil { 69 t.Fatalf("CompiledProgram did not report an error when decoding garbage") 70 } 71 if !strings.Contains(err.Error(), "not a compiled module") { 72 t.Fatalf("CompiledProgram reported the wrong error when decoding garbage: %v", err) 73 } 74 }