Skip to content

Commit d162325

Browse files
committed
wip: get new way to mock logs working in tests
1 parent f97b196 commit d162325

55 files changed

Lines changed: 1761 additions & 2732 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

lib/cli-entry.js

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
/* eslint-disable max-len */
2-
3-
// Separated out for easier unit testing
41
module.exports = async (process, validateEngines) => {
52
// set it here so that regardless of what happens later, we don't
63
// leak any private CLI configs to other programs
@@ -17,18 +14,25 @@ module.exports = async (process, validateEngines) => {
1714
const npm = new Npm()
1815
exitHandler.setNpm(npm)
1916

20-
// only log node and npm paths in argv initially since argv can contain sensitive info. a cleaned version will be logged later
17+
// only log node and npm paths in argv initially since argv can contain
18+
// sensitive info. a cleaned version will be logged later
2119
const log = require('proc-log')
2220
log.verbose('cli', process.argv.slice(0, 2).join(' '))
2321
log.info('using', 'npm@%s', npm.version)
2422
log.info('using', 'node@%s', process.version)
2523

26-
// At this point we've required a few files and can be pretty sure we dont contain invalid syntax for this version of node. It's possible a lazy require would, but that's unlikely enough that it's not worth catching anymore and we attach the more important exit handlers.
24+
// At this point we've required a few files and can be pretty sure we dont
25+
// contain invalid syntax for this version of node. It's possible a lazy
26+
// require would, but that's unlikely enough that it's not worth catching
27+
// anymore and we attach the more important exit handlers.
2728
validateEngines.off()
2829
process.on('uncaughtException', exitHandler)
2930
process.on('unhandledRejection', exitHandler)
3031

31-
// It is now safe to log a warning if they are using a version of node that is not going to fail on syntax errors but is still unsupported and untested and might not work reliably. This is safe to use the logger now which we want since this will show up in the error log too.
32+
// It is now safe to log a warning if they are using a version of node that is
33+
// not going to fail on syntax errors but is still unsupported and untested
34+
// and might not work reliably. This is safe to use the logger now which we
35+
// want since this will show up in the error log too.
3236
if (!satisfies(validateEngines.node, validateEngines.engines)) {
3337
log.warn('cli', validateEngines.unsupportedMessage)
3438
}

lib/commands/init.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ class Init extends BaseCommand {
6060
// to create a workspace package.json file or its folders
6161
const { content: pkg } = await PackageJson.normalize(this.npm.localPrefix).catch(err => {
6262
if (err.code === 'ENOENT') {
63-
log.warn('Missing package.json. Try with `--include-workspace-root`.')
63+
log.warn('', 'Missing package.json. Try with `--include-workspace-root`.')
6464
}
6565
throw err
6666
})

lib/commands/ping.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ class Ping extends BaseCommand {
1212
const cleanRegistry = cleanUrl(this.npm.config.get('registry'))
1313
log.notice('PING', cleanRegistry)
1414
const start = Date.now()
15-
const details = await pingUtil({ ...this.npm.flatOptions })
15+
let details = await pingUtil({ ...this.npm.flatOptions })
16+
details = { a: 1, b: 2 }
1617
const time = Date.now() - start
1718
log.notice('PONG', `${time}ms`)
1819
if (this.npm.config.get('json')) {
@@ -22,7 +23,7 @@ class Ping extends BaseCommand {
2223
details,
2324
}, null, 2))
2425
} else if (Object.keys(details).length) {
25-
log.notice('PONG', `${JSON.stringify(details, null, 2)}`)
26+
log.notice('PONG', JSON.stringify(details, null, 2))
2627
}
2728
}
2829
}

lib/npm.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ class Npm {
4848
#logChalk = null
4949
#noColorChalk = null
5050

51+
#display = null
5152
#logFile = new LogFile()
52-
#display = new Display()
5353
#timers = new Timers({
5454
start: 'npm',
5555
listener: (name, ms) => {
@@ -71,7 +71,14 @@ class Npm {
7171
// allows tests created by tap inside this repo to not set the local
7272
// prefix to `npmRoot` since that is the first dir it would encounter when
7373
// doing implicit detection
74-
constructor ({ npmRoot = dirname(__dirname), argv = [], excludeNpmCwd = false } = {}) {
74+
constructor ({
75+
stdout = process.stdout,
76+
stderr = process.stderr,
77+
npmRoot = dirname(__dirname),
78+
argv = [],
79+
excludeNpmCwd = false,
80+
} = {}) {
81+
this.#display = new Display({ stdout, stderr })
7582
this.#npmRoot = npmRoot
7683
this.config = new Config({
7784
npmPath: this.#npmRoot,
@@ -446,7 +453,7 @@ class Npm {
446453
}
447454

448455
outputBuffer (arg) {
449-
this.#display.outputBuffer.push(arg)
456+
this.#display.outputBuffer(arg)
450457
}
451458

452459
flushOutput (jsonError) {

lib/utils/display.js

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ const LEVEL_OPTIONS = {
5757
const LEVEL_METHODS = {
5858
...LEVEL_OPTIONS,
5959
[LEVELS.timing]: {
60-
show: ({ index, timing }) => timing && index !== 0,
60+
show: ({ timing, index }) => !!timing && index !== 0,
6161
},
6262
}
6363

@@ -68,7 +68,7 @@ const safeJsonParse = (maybeJsonStr) => {
6868
try {
6969
return JSON.parse(maybeJsonStr)
7070
} catch {
71-
return maybeJsonStr
71+
return {}
7272
}
7373
}
7474

@@ -93,7 +93,12 @@ class Display {
9393
#json = false
9494
#heading = 'npm'
9595

96-
constructor () {
96+
#stdout = null
97+
#stderr = null
98+
99+
constructor ({ stdout, stderr }) {
100+
this.#stdout = stdout
101+
this.#stderr = stderr
97102
process.on('log', this.#logHandler)
98103
}
99104

@@ -135,11 +140,11 @@ class Display {
135140

136141
output (...args) {
137142
// TODO: make this respect silent option
138-
process.stdout.write(format(...args))
143+
this.#stdout.write(format(...args))
139144
}
140145

141146
outputError (...args) {
142-
process.stderr.write(format(...args))
147+
this.#stderr.write(format(...args))
143148
}
144149

145150
outputBuffer (item) {
@@ -193,7 +198,7 @@ class Display {
193198
this.#colors[levelName](level.label ?? levelName),
194199
title ? this.#colors.title(title) : null,
195200
]
196-
process.stderr.write(formatWithOptions({ prefix }, ...args))
201+
this.#stderr.write(formatWithOptions({ prefix }, ...args))
197202
} else if (this.#progress) {
198203
// TODO: make this display a single log line of filtered messages
199204
}

lib/utils/exit-handler.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ process.on('exit', code => {
5757

5858
// Determine whether to show log file message and why it is
5959
// being shown since in timing mode we always show the log file message
60-
const logMethod = showLogFileError ? 'error' : timing ? 'info' : null
60+
const logMethod = showLogFileError ? 'error' : timing ? 'notice' : null
6161

6262
if (logMethod) {
6363
if (!npm.silent) {
@@ -121,7 +121,7 @@ const exitHandler = err => {
121121

122122
// only show the notification if it finished.
123123
if (typeof npm.updateNotification === 'string') {
124-
npm.forcceLog('notice', '', npm.updateNotification)
124+
npm.forceLog('notice', '', npm.updateNotification)
125125
}
126126

127127
let exitCode = process.exitCode || 0

lib/utils/format.js

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -85,15 +85,11 @@ const cleanControl = createCleaner((output) => {
8585
})
8686

8787
const formatWithOptions = ({ prefix = [], eol = '\n', ...options }, ...args) => {
88-
const prefixStr = prefix.filter(p => p != null).join(' ')
88+
const pre = prefix.filter(p => p != null).join(' ')
8989
return baseFormatWithOptions(options, ...args)
90-
.trim()
9190
.split(/\r?\n/)
9291
.map(cleanControl)
93-
.reduce((lines, line) =>
94-
lines += prefixStr + (prefixStr && line ? ' ' : '') + line + eol,
95-
''
96-
)
92+
.reduce((acc, l) => `${acc}${pre}${pre && l ? ' ' : ''}${l}${eol}`, '')
9793
}
9894

9995
const format = (...args) => formatWithOptions({}, ...args)

lib/utils/log-file.js

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,6 @@ class LogFiles {
4141
this.on()
4242
}
4343

44-
static format (count, level, title, ...args) {
45-
const prefix = [count, level, title || null]
46-
return formatWithOptions({ prefix, eol: os.EOL, colors: false }, ...args)
47-
}
48-
4944
on () {
5045
this.#logStream = new Minipass()
5146
process.on('log', this.#logHandler)
@@ -141,9 +136,10 @@ class LogFiles {
141136
}
142137
}
143138

144-
#formatLogItem (...args) {
139+
#formatLogItem (level, title, ...args) {
145140
this.#fileLogCount += 1
146-
return LogFiles.format(this.#totalLogCount++, ...args)
141+
const prefix = [this.#totalLogCount++, level, title || null]
142+
return formatWithOptions({ prefix, eol: os.EOL, colors: false }, ...args)
147143
}
148144

149145
#getLogFilePath (count = '') {

tap-snapshots/test/lib/commands/audit.js.test.cjs

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ exports[`test/lib/commands/audit.js TAP audit signatures ignores optional depend
4545
audited 1 package in xxx
4646
4747
1 package has a verified registry signature
48-
4948
`
5049

5150
exports[`test/lib/commands/audit.js TAP audit signatures json output with invalid and missing signatures > must match snapshot 1`] = `
@@ -131,14 +130,12 @@ exports[`test/lib/commands/audit.js TAP audit signatures multiple registries wit
131130
audited 2 packages in xxx
132131
133132
2 packages have verified registry signatures
134-
135133
`
136134

137135
exports[`test/lib/commands/audit.js TAP audit signatures omit dev dependencies with missing signature > must match snapshot 1`] = `
138136
audited 1 package in xxx
139137
140138
1 package has a verified registry signature
141-
142139
`
143140

144141
exports[`test/lib/commands/audit.js TAP audit signatures output details about missing signatures > must match snapshot 1`] = `
@@ -157,7 +154,6 @@ audited 1 package in xxx
157154
@npmcli/arborist@1.0.14 (https://verdaccio-clone.org/)
158155
159156
Someone might have tampered with this package since it was published on the registry!
160-
161157
`
162158

163159
exports[`test/lib/commands/audit.js TAP audit signatures third-party registry with keys and missing signatures errors > must match snapshot 1`] = `
@@ -172,21 +168,18 @@ exports[`test/lib/commands/audit.js TAP audit signatures third-party registry wi
172168
audited 1 package in xxx
173169
174170
1 package has a verified registry signature
175-
176171
`
177172

178173
exports[`test/lib/commands/audit.js TAP audit signatures third-party registry with sub-path (trailing slash) > must match snapshot 1`] = `
179174
audited 1 package in xxx
180175
181176
1 package has a verified registry signature
182-
183177
`
184178

185179
exports[`test/lib/commands/audit.js TAP audit signatures third-party registry with sub-path > must match snapshot 1`] = `
186180
audited 1 package in xxx
187181
188182
1 package has a verified registry signature
189-
190183
`
191184

192185
exports[`test/lib/commands/audit.js TAP audit signatures with both invalid and missing signatures > must match snapshot 1`] = `
@@ -201,14 +194,12 @@ async@1.1.1 (https://registry.npmjs.org/)
201194
kms-demo@1.0.0 (https://registry.npmjs.org/)
202195
203196
Someone might have tampered with this package since it was published on the registry!
204-
205197
`
206198

207199
exports[`test/lib/commands/audit.js TAP audit signatures with bundled and peer deps and no signatures > must match snapshot 1`] = `
208200
audited 1 package in xxx
209201
210202
1 package has a verified registry signature
211-
212203
`
213204

214205
exports[`test/lib/commands/audit.js TAP audit signatures with invalid attestations > must match snapshot 1`] = `
@@ -219,7 +210,6 @@ audited 1 package in xxx
219210
sigstore@1.0.0 (https://registry.npmjs.org/)
220211
221212
Someone might have tampered with this package since it was published on the registry!
222-
223213
`
224214

225215
exports[`test/lib/commands/audit.js TAP audit signatures with invalid signatures > must match snapshot 1`] = `
@@ -230,7 +220,6 @@ audited 1 package in xxx
230220
kms-demo@1.0.0 (https://registry.npmjs.org/)
231221
232222
Someone might have tampered with this package since it was published on the registry!
233-
234223
`
235224

236225
exports[`test/lib/commands/audit.js TAP audit signatures with invalid signtaures and color output enabled > must match snapshot 1`] = `
@@ -241,14 +230,12 @@ audited 1 package in xxx
241230
kms-demo@1.0.0 (https://registry.npmjs.org/)
242231
243232
Someone might have tampered with this package since it was published on the registry!
244-
245233
`
246234

247235
exports[`test/lib/commands/audit.js TAP audit signatures with key fallback to legacy API > must match snapshot 1`] = `
248236
audited 1 package in xxx
249237
250238
1 package has a verified registry signature
251-
252239
`
253240

254241
exports[`test/lib/commands/audit.js TAP audit signatures with keys but missing signature > must match snapshot 1`] = `
@@ -268,7 +255,6 @@ sigstore@1.0.0 (https://registry.npmjs.org/)
268255
tuf-js@1.0.0 (https://registry.npmjs.org/)
269256
270257
Someone might have tampered with these packages since they were published on the registry!
271-
272258
`
273259

274260
exports[`test/lib/commands/audit.js TAP audit signatures with multiple invalid signatures > must match snapshot 1`] = `
@@ -280,7 +266,6 @@ async@1.1.1 (https://registry.npmjs.org/)
280266
kms-demo@1.0.0 (https://registry.npmjs.org/)
281267
282268
Someone might have tampered with these packages since they were published on the registry!
283-
284269
`
285270

286271
exports[`test/lib/commands/audit.js TAP audit signatures with multiple missing signatures > must match snapshot 1`] = `
@@ -302,7 +287,6 @@ audited 3 packages in xxx
302287
node-fetch@1.6.0 (https://registry.npmjs.org/)
303288
304289
Someone might have tampered with this package since it was published on the registry!
305-
306290
`
307291

308292
exports[`test/lib/commands/audit.js TAP audit signatures with valid and missing signatures > must match snapshot 1`] = `
@@ -321,35 +305,30 @@ audited 1 package in xxx
321305
1 package has a verified registry signature
322306
323307
1 package has a verified attestation
324-
325308
`
326309

327310
exports[`test/lib/commands/audit.js TAP audit signatures with valid signatures > must match snapshot 1`] = `
328311
audited 1 package in xxx
329312
330313
1 package has a verified registry signature
331-
332314
`
333315

334316
exports[`test/lib/commands/audit.js TAP audit signatures with valid signatures using alias > must match snapshot 1`] = `
335317
audited 1 package in xxx
336318
337319
1 package has a verified registry signature
338-
339320
`
340321

341322
exports[`test/lib/commands/audit.js TAP audit signatures workspaces verifies registry deps and ignores local workspace deps > must match snapshot 1`] = `
342323
audited 3 packages in xxx
343324
344325
3 packages have verified registry signatures
345-
346326
`
347327

348328
exports[`test/lib/commands/audit.js TAP audit signatures workspaces verifies registry deps when filtering by workspace name > must match snapshot 1`] = `
349329
audited 2 packages in xxx
350330
351331
2 packages have verified registry signatures
352-
353332
`
354333

355334
exports[`test/lib/commands/audit.js TAP fallback audit > must match snapshot 1`] = `

0 commit comments

Comments
 (0)