Repository navigation
Expand file tree
/
Copy patherrorstack_unix_test.go
More file actions
90 lines (76 loc) · 1.79 KB
/
Copy patherrorstack_unix_test.go
File metadata and controls
90 lines (76 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Copyright (c) 2026 The slowjs Authors.
// SPDX-License-Identifier: MIT
// Use of this source code is governed by the MIT license in LICENSE-MIT at the
// root of this repository.
//go:build unix
package slowjs // import "github.com/liustack/slowjs"
import (
"io"
"os"
"testing"
"golang.org/x/sys/unix"
)
// TestErrorStackPrint checks the stack console.log prints with an error, which
// the engine reads without running any JS code. printed is called from Go, so
// that no top-level code is on the stack and the stack is not formatted yet.
func TestErrorStackPrint(t *testing.T) {
m, err := NewVM()
if err != nil {
t.Fatal(err)
}
defer m.Close()
if err := m.StdAddHelpers(); err != nil {
t.Fatal(err)
}
if _, err := m.Eval(`function printed() {
var e = new Error("printed")
console.log(e)
console.log([e], { err: new TypeError("inner") })
e.stack
console.log(e)
}`, EvalGlobal); err != nil {
t.Fatal(err)
}
got := captureStdout(t, func() {
if _, err := m.Call("printed"); err != nil {
t.Error(err)
}
})
want := `Error: printed
at printed (<eval>:2:19)
[ Error: printed
at printed (<eval>:2:19) ] { err: TypeError: inner
at printed (<eval>:4:39) }
Error: printed
at printed (<eval>:2:19)
`
if got != want {
t.Errorf("got\n%s\nwant\n%s", got, want)
}
}
// captureStdout returns what f writes to file descriptor 1.
func captureStdout(t *testing.T, f func()) string {
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
saved, err := unix.Dup(1)
if err != nil {
t.Fatal(err)
}
if err := unix.Dup2(int(w.Fd()), 1); err != nil {
t.Fatal(err)
}
done := make(chan string)
go func() {
b, _ := io.ReadAll(r)
done <- string(b)
}()
f()
if err := unix.Dup2(saved, 1); err != nil {
t.Fatal(err)
}
unix.Close(saved)
w.Close()
return <-done
}