package ph7_test import ( "bytes" "errors" "fmt" "testing" ph7 "git.codemonkeysoftware.net/b/go-ph7" ) func mustSucceed(t *testing.T, err error) { t.Helper() if err != nil { t.Fatal(err.Error()) } } func mustFail(t *testing.T, err error) { t.Helper() if err == nil { t.Fatal("expected error, got nil") } } func mustSucceedF(t *testing.T, f func() error) { t.Helper() err := f() if err != nil { t.Fatal(err.Error()) } } func TestCore(t *testing.T) { engine, err := ph7.NewEngine() mustSucceed(t, err) defer mustSucceedF(t, engine.Close) vm, err := engine.Compile([]byte(""), false) mustSucceed(t, err) defer mustSucceedF(t, vm.Close) mustSucceed(t, vm.Exec()) output, err := vm.ExtractOutput() mustSucceed(t, err) if output != "Hello world!" { t.Fatalf("unexpected output: %s", output) } mustSucceed(t, vm.Reset()) mustSucceed(t, vm.Exec()) output, err = vm.ExtractOutput() mustSucceed(t, err) if output != "Hello world!" { t.Fatalf("unexpected output: %s", output) } } func TestCompileError(t *testing.T) { engine, err := ph7.NewEngine() mustSucceed(t, err) defer mustSucceedF(t, engine.Close) _, err = engine.Compile([]byte(""), false) mustFail(t, err) var target ph7.CompileError isCompileError := errors.As(err, &target) if !isCompileError || target.Msg == "" { t.Fatalf("expected compile error, got %#v", err) } } func TestOutputWriter(t *testing.T) { const source = `` var expected bytes.Buffer for i := 0; i <= 1000; i++ { _, err := fmt.Fprint(&expected, i) mustSucceed(t, err) } engine, err := ph7.NewEngine() mustSucceed(t, err) defer mustSucceedF(t, engine.Close) vm, err := engine.Compile([]byte(source), false) mustSucceed(t, err) defer vm.Close() var actual bytes.Buffer err = vm.SetOutputWriter(&actual) mustSucceed(t, err) mustSucceed(t, vm.Exec()) if !bytes.Equal(expected.Bytes(), actual.Bytes()) { t.Fatalf("expected %s, got %s", expected.String(), actual.String()) } } // TODO Test failing writer, including vm.OutputWriteError // TODO Test setting writer twice