v7
1// Copyright 2022 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 { suite } from 'uvu'
16import * as assert from 'uvu/assert'
17import {
18 exitCodeInfo,
19 errnoMessage,
20 formatCmd,
21 isString,
22 noop,
23 parseDuration,
24 quote,
25 quotePowerShell,
26 randomId,
27} from '../build/util.js'
28
29const test = suite('util')
30
31test('exitCodeInfo()', () => {
32 assert.is(exitCodeInfo(2), 'Misuse of shell builtins')
33})
34
35test('errnoMessage()', () => {
36 assert.is(errnoMessage(-2), 'No such file or directory')
37 assert.is(errnoMessage(1e9), 'Unknown error')
38 assert.is(errnoMessage(undefined), 'Unknown error')
39})
40
41test('randomId()', () => {
42 assert.ok(/^[a-z0-9]+$/.test(randomId()))
43 assert.ok(
44 new Set(Array.from({ length: 1000 }).map(() => randomId())).size === 1000
45 )
46})
47
48test('noop()', () => {
49 assert.ok(noop() === undefined)
50})
51
52test('isString()', () => {
53 assert.ok(isString('string'))
54 assert.not.ok(isString(1))
55})
56
57test('quote()', () => {
58 assert.ok(quote('string') === 'string')
59 assert.ok(quote(`'\f\n\r\t\v\0`) === `$'\\'\\f\\n\\r\\t\\v\\0'`)
60})
61
62test('quotePowerShgell()', () => {
63 assert.is(quotePowerShell('string'), 'string')
64 assert.is(quotePowerShell(`'`), `''''`)
65})
66
67test('duration parsing works', () => {
68 assert.is(parseDuration(1000), 1000)
69 assert.is(parseDuration('2s'), 2000)
70 assert.is(parseDuration('500ms'), 500)
71 assert.throws(() => parseDuration('100'))
72 assert.throws(() => parseDuration(NaN))
73 assert.throws(() => parseDuration(-1))
74})
75
76test('formatCwd works', () => {
77 assert.is(
78 formatCmd(`echo $'hi'`),
79 "$ \u001b[92mecho\u001b[39m \u001b[93m$\u001b[39m\u001b[93m'hi\u001b[39m\u001b[93m'\u001b[39m\n"
80 )
81 assert.is(
82 formatCmd(`while true; do "$" done`),
83 '$ \u001b[96mwhile\u001b[39m \u001b[92mtrue\u001b[39m\u001b[96m;\u001b[39m \u001b[96mdo\u001b[39m \u001b[93m"$\u001b[39m\u001b[93m"\u001b[39m \u001b[96mdone\u001b[39m\n'
84 )
85 assert.is(
86 formatCmd(`echo '\n str\n'`),
87 "$ \u001b[92mecho\u001b[39m \u001b[93m'\u001b[39m\n> \u001b[93m str\u001b[39m\n> \u001b[93m'\u001b[39m\n"
88 )
89 assert.is(
90 formatCmd(`$'\\''`),
91 "$ \u001b[93m$\u001b[39m\u001b[93m'\u001b[39m\u001b[93m\\\u001b[39m\u001b[93m'\u001b[39m\u001b[93m'\u001b[39m\n"
92 )
93})
94
95test.run()