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