main
1// Copyright 2024 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import assert from 'assert'
16import 'zx/globals'
17;(async () => {
18 // smoke test
19 {
20 const p = await $`echo foo`
21 assert.match(p.stdout, /foo/)
22 assert.deepEqual(p.lines(), ['foo'])
23 }
24
25 // captures err stack
26 {
27 const p = await $({ nothrow: true })`echo foo; exit 3`
28 assert.match(p.message, /exit code: 3/)
29 }
30
31 // ctx isolation
32 {
33 await within(async () => {
34 const t1 = tmpdir()
35 const t3 = tmpdir()
36 $.cwd = t1
37 assert.equal($.cwd, t1)
38 assert.equal($.cwd, t1)
39
40 const w = within(async () => {
41 const t3 = tmpdir()
42 $.cwd = t3
43 assert.equal($.cwd, t3)
44
45 assert.ok((await $`pwd`).toString().trim().endsWith(t3))
46 assert.equal($.cwd, t3)
47 })
48
49 await $`pwd`
50 assert.ok((await $`pwd`).toString().trim().endsWith(t1))
51 assert.equal($.cwd, t1)
52 assert.ok((await $`pwd`).toString().trim().endsWith(t1))
53
54 $.cwd = t3
55 assert.ok((await $`pwd`).toString().trim().endsWith(t3))
56 assert.equal($.cwd, t3)
57
58 await w
59 })
60 }
61
62 // ps works fine
63 {
64 const [root] = await ps.lookup({ pid: process.pid })
65 assert.equal(root.pid, process.pid)
66 }
67
68 // abort controller
69 {
70 const ac = new AbortController()
71 const { signal } = ac
72 const p = $({
73 signal,
74 timeout: '5s',
75 nothrow: true,
76 killSignal: 'SIGKILL',
77 })`sleep 10`
78
79 setTimeout(async () => {
80 assert.throws(
81 () => p.abort('SIGINT'),
82 /signal is controlled by another process/
83 )
84 setTimeout(() => {
85 ac.abort('stop')
86 }, 500)
87 }, 500)
88
89 const o = await p
90 assert.equal(o.signal, 'SIGTERM')
91 assert.throws(() => p.kill(), /Too late to kill the process/)
92 }
93
94 // fetch()
95 {
96 const server = (await import('../fixtures/server.mjs')).fakeServer([
97 `HTTP/1.1 200 OK
98Content-Type: application/json
99Content-Length: 13
100Server: netcat!
101
102{"foo":"bar"}
103`,
104 ])
105
106 const { url } = await server.start(8081)
107 const res = await fetch(url)
108 const json = await res.json()
109 assert.equal(res.status, 200)
110 assert.equal(json.foo, 'bar')
111
112 await server.stop()
113 }
114
115 console.log('smoke mjs: ok')
116})()