89 lines
2.4 KiB
Go
89 lines
2.4 KiB
Go
package runtime
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
"modernc.org/quickjs"
|
|
"reichard.io/poiesis/internal/functions"
|
|
)
|
|
|
|
type TestArgs struct {
|
|
Field1 string `json:"field1"`
|
|
}
|
|
|
|
func (t TestArgs) Validate() error {
|
|
return nil
|
|
}
|
|
|
|
func TestExecuteTypeScript(t *testing.T) {
|
|
var stdout, stderr bytes.Buffer
|
|
|
|
rt, err := New(context.Background(), WithStderr(&stderr), WithStdout(&stdout))
|
|
assert.NoError(t, err, "Expected no error")
|
|
|
|
err = rt.RunFile("../../test_data/test.ts")
|
|
|
|
assert.NoError(t, err, "Expected no error")
|
|
assert.Empty(t, stderr.String(), "Expected no error output")
|
|
|
|
output := stdout.String()
|
|
|
|
assert.Contains(t, output, "Hello, Alice!", "Should greet Alice")
|
|
assert.Contains(t, output, "You are 30 years old", "Should show age")
|
|
assert.Contains(t, output, "Email: alice@example.com", "Should show email")
|
|
assert.Contains(t, output, "Sum of 5 and 10 is: 15", "Should calculate sum correctly")
|
|
|
|
lines := strings.Split(strings.TrimSpace(output), "\n")
|
|
assert.GreaterOrEqual(t, len(lines), 3, "Should have at least 3 output lines")
|
|
}
|
|
|
|
func TestAsyncFunctionResolution(t *testing.T) {
|
|
functions.RegisterAsyncFunction("resolveTest", func(_ context.Context, args TestArgs) (string, error) {
|
|
return "test-result", nil
|
|
})
|
|
|
|
r, err := New(context.Background())
|
|
require.NoError(t, err)
|
|
|
|
result, err := r.vm.Eval(`resolveTest("hello")`, quickjs.EvalGlobal)
|
|
require.NoError(t, err)
|
|
assert.NotNil(t, result)
|
|
}
|
|
|
|
func TestAsyncFunctionRejection(t *testing.T) {
|
|
functions.RegisterAsyncFunction("rejectTest", func(_ context.Context, args TestArgs) (string, error) {
|
|
return "", assert.AnError
|
|
})
|
|
|
|
r, err := New(context.Background())
|
|
require.NoError(t, err)
|
|
|
|
result, err := r.vm.Eval(`rejectTest({field1: "hello"})`, quickjs.EvalGlobal)
|
|
require.NoError(t, err)
|
|
assert.NotNil(t, result)
|
|
}
|
|
|
|
func TestNonPromise(t *testing.T) {
|
|
functions.RegisterFunction("nonPromiseTest", func(_ context.Context, args TestArgs) (string, error) {
|
|
return "sync-result", nil
|
|
})
|
|
|
|
r, err := New(context.Background())
|
|
require.NoError(t, err)
|
|
|
|
result, err := r.vm.Eval(`nonPromiseTest({field1: "hello"})`, quickjs.EvalGlobal)
|
|
require.NoError(t, err)
|
|
|
|
if obj, ok := result.(*quickjs.Object); ok {
|
|
var arr []any
|
|
if err := obj.Into(&arr); err == nil && len(arr) > 0 {
|
|
assert.Equal(t, "sync-result", arr[0])
|
|
}
|
|
}
|
|
}
|