forked from google/zx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.mjs
executable file
·244 lines (208 loc) · 6.3 KB
/
test.mjs
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {strict as assert} from 'assert'
import {retry} from './experimental.mjs'
{ // Only stdout is used during command substitution
let hello = await $`echo Error >&2; echo Hello`
let len = +(await $`echo ${hello} | wc -c`)
assert(len === 6)
}
{ // Pass env var
process.env.FOO = 'foo'
let foo = await $`echo $FOO`
assert(foo.stdout === 'foo\n')
}
{ // Arguments are quoted
let bar = 'bar"";baz!$#^$\'&*~*%)({}||\\/'
assert((await $`echo ${bar}`).stdout.trim() === bar)
}
{ // Undefined and empty string correctly quoted
$`echo ${undefined}`
$`echo ${''}`
}
{ // Can create a dir with a space in the name
let name = 'foo bar'
try {
await $`mkdir /tmp/${name}`
} finally {
await fs.rmdir('/tmp/' + name)
}
}
{ // Pipefail is on
let p
try {
p = await $`cat /dev/not_found | sort`
} catch (e) {
console.log('Caught an exception -> ok')
p = e
}
assert(p.exitCode !== 0)
}
{ // Env vars is safe to pass
process.env.FOO = 'hi; exit 1'
await $`echo $FOO`
}
{ // Globals are defined
console.log(__filename, __dirname)
}
{ // toString() is called on arguments
let foo = 0
let p = await $`echo ${foo}`
assert(p.stdout === '0\n')
}
{ // Can use array as an argument
try {
let files = ['./index.mjs', './zx.mjs', './package.json']
await $`tar czf archive ${files}`
} finally {
await $`rm archive`
}
}
{ // Scripts with no extension work and do not overwrite similarly named files.
await $`node zx.mjs tests/no-extension`
assert.match((await fs.readFile('tests/no-extension.mjs')).toString(), /Test file to verify no-extension didn't overwrite similarly name .mjs file./);
}
{ // require() is working from stdin
await $`node zx.mjs <<< 'require("./package.json").name'`
}
{ // Markdown scripts are working
await $`node zx.mjs docs/markdown.md`
}
{ // Quiet mode is working
let {stdout} = await $`node zx.mjs --quiet docs/markdown.md`
assert(!stdout.includes('whoami'))
}
{ // Pipes are working
let {stdout} = await $`echo "hello"`
.pipe($`awk '{print $1" world"}'`)
.pipe($`tr '[a-z]' '[A-Z]'`)
assert(stdout === 'HELLO WORLD\n')
try {
let w = await $`echo foo`
.pipe(fs.createWriteStream('/tmp/output.txt'))
assert((await fs.readFile('/tmp/output.txt')).toString() === 'foo\n')
let r = $`cat`
fs.createReadStream('/tmp/output.txt')
.pipe(r.stdin)
assert((await r).stdout === 'foo\n')
} finally {
await fs.rm('/tmp/output.txt')
}
}
{ // ProcessOutput thrown as error
let err
try {
await $`wtf`
} catch (p) {
err = p
}
console.error(err)
assert(err.exitCode > 0)
console.error('☝️ Error above is expected')
}
{ // The pipe() throws if already resolved
let out, p = $`echo "Hello"`
await p
try {
out = await p.pipe($`less`)
} catch (err) {
console.log(err)
assert.equal(err.message, `The pipe() method shouldn't be called after promise is already resolved!`)
console.log('☝️ Error above is expected')
}
if (out) {
assert.fail('Expected failure!')
}
}
{ // ProcessOutput::exitCode doesn't throw
assert(await $`grep qwerty README.md`.exitCode !== 0)
assert(await $`[[ -f ${__filename} ]]`.exitCode === 0)
}
{ // nothrow() doesn't throw
let {exitCode} = await nothrow($`exit 42`)
assert(exitCode === 42)
}
{ // globby available
assert(globby === glob)
assert(typeof globby === 'function')
assert(typeof globby.globbySync === 'function')
assert(typeof globby.globbyStream === 'function')
assert(typeof globby.generateGlobTasks === 'function')
assert(typeof globby.isDynamicPattern === 'function')
assert(typeof globby.isGitIgnored === 'function')
assert(typeof globby.isGitIgnoredSync === 'function')
console.log(chalk.greenBright('globby available'))
}
{ // Executes a script from PATH.
const isWindows = process.platform === 'win32'
const oldPath = process.env.PATH
const envPathSeparator = isWindows ? ';' : ':'
process.env.PATH += envPathSeparator + path.resolve('/tmp/')
const toPOSIXPath = (_path) =>
_path.split(path.sep).join(path.posix.sep)
const zxPath = path.resolve('./zx.mjs')
const zxLocation = isWindows ? toPOSIXPath(zxPath) : zxPath
const scriptCode = `#!/usr/bin/env ${zxLocation}\nconsole.log('The script from path runs.')`
try {
await $`echo ${scriptCode}`
.pipe(fs.createWriteStream('/tmp/script-from-path', {mode: 0o744}))
await $`script-from-path`
} finally {
process.env.PATH = oldPath
fs.rmSync('/tmp/script-from-path')
}
}
{ // cd() works with relative paths.
try {
fs.mkdirpSync('/tmp/zx-cd-test/one/two')
cd('/tmp/zx-cd-test/one/two')
cd('..')
cd('..')
let pwd = (await $`pwd`).stdout.trim()
assert.equal(path.basename(pwd), 'zx-cd-test')
} finally {
fs.rmSync('/tmp/zx-cd-test', {recursive: true})
cd(__dirname)
}
}
{ // The kill() method works.
let p = nothrow($`sleep 9999`)
setTimeout(() => {
p.kill()
}, 100)
await p
}
{ // YAML works.
assert.deepEqual(YAML.parse(YAML.stringify({foo: 'bar'})), {foo: 'bar'})
console.log(chalk.greenBright('YAML works'))
}
{ // Retry works.
try {
await retry(5)`exit 123`
} catch (p) {
assert.equal(p.exitCode, 123)
}
}
{ // require() is working in ESM
const {name, version} = require('./package.json')
assert(typeof name === 'string')
console.log(chalk.whiteBright.bgYellow(` ${name} version is ${version} `))
}
// require() is working in ESM with namespaced exports @theorylabs/zx/pkg
{
const {name, version, exports} = require('@theorylabs/zx/package-manifest')
assert(typeof name === 'string')
console.log(chalk.whiteBright.bgCyan(` ${name} version is ${version} with exports: ${require('util').inspect(exports, { showHidden: true, depth: null })}`))
}
console.log(chalk.greenBright(' 🍺 Success!'))