-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathindex.test.js
More file actions
534 lines (479 loc) · 22.2 KB
/
Copy pathindex.test.js
File metadata and controls
534 lines (479 loc) · 22.2 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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { debug, run } from './index.js'
import { pickJob, legacyArtifactsUrl, redirectUrl, statusFor, fetchJson, resolveStatus } from './src/core.js'
import { normalizeConfig } from './src/config.js'
const INPUTS = ['artifact-path', 'repo-token', 'api-token', 'circleci-jobs', 'job-title', 'domain', 'post-pending', 'no-artifact-state']
const OUTPUT_FILE = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'redirector-')), 'output.txt')
const ARTIFACT = {url: 'https://output.circle-artifacts.com/output/job/abc/artifacts/0/doc/other.html'}
// Run the action against fake CircleCI/GitHub backends. `bodies` are returned
// by successive fetch() calls, and the recorded requests, the `url` output and
// the commit status that was created are handed back for inspection.
async function runAction({inputs = {}, payload = {}, bodies = [], fetchError, httpStatus = 200} = {}) {
fs.writeFileSync(OUTPUT_FILE, '')
process.env.GITHUB_OUTPUT = OUTPUT_FILE
for (const name of INPUTS) {
delete process.env[`INPUT_${name.toUpperCase()}`]
}
const all = {'artifact-path': 'doc/index.html', 'repo-token': 'gh-token', domain: 'output.circle-artifacts.com', ...inputs}
for (const [name, value] of Object.entries(all)) {
process.env[`INPUT_${name.toUpperCase()}`] = value
}
const requests = []
const fetchFn = async (url, options) => {
requests.push({url, options})
if (fetchError !== undefined) {
throw fetchError
}
return {
ok: httpStatus < 400,
status: httpStatus,
json: async () => bodies.shift(),
text: async () => JSON.stringify(bodies.shift()),
}
}
let status = null
const getOctokit = () => ({rest: {repos: {createCommitStatus: async (s) => { status = s }}}})
const context = {
payload: {
context: 'ci/circleci: build',
state: 'success',
sha: 'deadbeef',
target_url: 'https://circleci.com/gh/scientific-python/circleci-artifacts-redirector-action/94',
...payload,
},
repo: {owner: 'scientific-python', repo: 'circleci-artifacts-redirector-action'},
}
// Capture the workflow commands instead of letting them reach the real
// stdout. The error-path tests make run() call core.setFailed(), which emits
// `::error::<message>`; on a runner that is parsed out of the step's output
// and posted as a failure annotation, so a green CI run grew three red
// annotations reading "kaboom" and friends. Returned so tests can assert on
// it, which several do.
const out = await captureStdout(() => run({context, fetchFn, getOctokit}))
const url = fs.readFileSync(OUTPUT_FILE, 'utf8').split(os.EOL)[1]
return {requests, url, status, out}
}
// Collect everything written to stdout (the ::debug::/::error:: workflow
// commands) while fn runs.
async function captureStdout(fn) {
const written = []
const original = process.stdout.write
process.stdout.write = (chunk) => { written.push(String(chunk)); return true }
try {
await fn()
} finally {
process.stdout.write = original
}
return written.join('')
}
test('legacy CircleCI URL', async () => {
const {requests, url, status} = await runAction({bodies: [{items: [ARTIFACT]}]})
assert.equal(requests.length, 1)
assert.equal(requests[0].url, 'https://circleci.com/api/v2/project/gh/scientific-python/circleci-artifacts-redirector-action/94/artifacts')
assert.ok(!('Circle-Token' in requests[0].options.headers), 'no token header without an api-token')
assert.equal(url, 'https://output.circle-artifacts.com/output/job/abc/artifacts/doc/index.html')
assert.deepEqual(status, {
repo: 'circleci-artifacts-redirector-action',
owner: 'scientific-python',
sha: 'deadbeef',
state: 'success',
target_url: url,
description: 'Link to doc/index.html',
context: 'ci/circleci: build artifact',
})
})
test('api token, custom domain and job title', async () => {
const {requests, url, status} = await runAction({
inputs: {'api-token': 'circle-token', domain: 'circleci-artifacts.scientific-python.org', 'job-title': 'See the docs'},
payload: {state: 'pending'},
bodies: [{items: [ARTIFACT]}],
})
assert.equal(requests[0].options.headers['Circle-Token'], 'circle-token')
assert.equal(url, 'https://circleci-artifacts.scientific-python.org/output/job/abc/artifacts/doc/index.html')
assert.equal(status.description, 'Waiting for CircleCI ...')
assert.equal(status.context, 'See the docs')
})
test('workflow URL with a single job', async () => {
const {requests, url} = await runAction({
payload: {target_url: 'https://app.circleci.com/workflow/wf-123?utm_source=github-build-link'},
bodies: [{items: [{name: 'other', project_slug: 'circleci/1/2', job_number: 7}]}, {items: [ARTIFACT]}],
})
assert.deepEqual(requests.map(r => r.url), [
'https://circleci.com/api/v2/workflow/wf-123/job',
'https://circleci.com/api/v2/project/circleci/1/2/7/artifacts',
])
assert.equal(url, 'https://output.circle-artifacts.com/output/job/abc/artifacts/doc/index.html')
})
test('workflow URL selects the matching job', async () => {
const jobs = [
{name: 'lint', project_slug: 'circleci/1/2', job_number: 7},
{name: 'docs', project_slug: 'circleci/1/2', job_number: 8},
]
const {requests} = await runAction({
inputs: {'circleci-jobs': 'docs'},
payload: {context: 'ci/circleci: docs', target_url: 'https://app.circleci.com/pipelines/circleci/1/2/3/workflows/wf-123'},
bodies: [{items: jobs}, {items: [ARTIFACT]}],
})
assert.equal(requests[1].url, 'https://circleci.com/api/v2/project/circleci/1/2/8/artifacts')
})
test('workflow URL falls back to the first job', async () => {
const jobs = [
{name: 'lint', project_slug: 'circleci/1/2', job_number: 7},
{name: 'test', project_slug: 'circleci/1/2', job_number: 8},
]
const {requests} = await runAction({
payload: {target_url: 'https://app.circleci.com/pipelines/circleci/1/2/3/workflows/wf-123'},
bodies: [{items: jobs}, {items: [ARTIFACT]}],
})
assert.equal(requests[1].url, 'https://circleci.com/api/v2/project/circleci/1/2/7/artifacts')
})
test('no artifacts links to the job itself and fails', async () => {
const {url, status} = await runAction({
inputs: {domain: 'circleci-artifacts.scientific-python.org'},
bodies: [{items: []}],
})
assert.equal(url, 'https://circleci.com/gh/scientific-python/circleci-artifacts-redirector-action/94')
assert.equal(status.target_url, url)
assert.equal(status.state, 'failure')
assert.equal(status.description, 'No artifacts found')
})
// gh-57: the status tracks the link, not the CircleCI job
test('a failed job with artifacts still succeeds', async () => {
const {url, status} = await runAction({
payload: {state: 'failure'},
bodies: [{items: [ARTIFACT]}],
})
assert.equal(url, 'https://output.circle-artifacts.com/output/job/abc/artifacts/doc/index.html')
assert.equal(status.state, 'success')
assert.equal(status.description, 'Link to doc/index.html')
})
test('a successful job without artifacts fails', async () => {
const {status} = await runAction({payload: {state: 'success'}, bodies: [{items: []}]})
assert.equal(status.state, 'failure')
})
test('a pending job stays pending', async () => {
const {status} = await runAction({payload: {state: 'pending'}, bodies: [{items: []}]})
assert.equal(status.state, 'pending')
assert.equal(status.description, 'Waiting for CircleCI ...')
})
test('other contexts are ignored', async () => {
const {requests, url, status} = await runAction({payload: {context: 'ci/circleci: lint'}})
assert.deepEqual(requests, [])
assert.equal(url, undefined)
assert.equal(status, null)
})
test('an empty workflow fails the job', async () => {
const {status, out} = await runAction({
payload: {target_url: 'https://app.circleci.com/workflow/wf-123'},
bodies: [{items: []}],
})
assert.equal(status, null)
assert.equal(process.exitCode, 1) // core.setFailed()
assert.match(out, /::error::No jobs returned/, 'captured, not left for the runner to annotate')
process.exitCode = 0
})
test('a bad response fails the job', async () => {
const {status, out} = await runAction({bodies: [undefined]}) // json() -> undefined
assert.equal(status, null)
assert.equal(process.exitCode, 1) // core.setFailed()
process.exitCode = 0
assert.match(out, /::error::/, 'captured, not left for the runner to annotate')
})
test('a thrown non-Error fails the job', async () => {
const {status, out} = await runAction({fetchError: 'kaboom'})
assert.equal(status, null)
assert.equal(process.exitCode, 1) // core.setFailed()
process.exitCode = 0
assert.match(out, /::error::kaboom/, 'captured, not left for the runner to annotate')
})
// Unit tests for the pieces run() is built from
test('pickJob', () => {
const lint = {name: 'lint'}
const docs = {name: 'docs'}
assert.equal(pickJob([lint], ['docs']), lint, 'a lone job is used even if unnamed')
assert.equal(pickJob([lint, docs], ['docs']), docs, 'a named job wins over an earlier one')
assert.equal(pickJob([lint, docs], ['nope']), lint, 'no match falls back to the first job')
})
test('legacyArtifactsUrl', () => {
assert.equal(
legacyArtifactsUrl('https://circleci.com/gh/mne-tools/mne-python/53315'),
'https://circleci.com/api/v2/project/gh/mne-tools/mne-python/53315/artifacts',
)
})
test('redirectUrl', () => {
assert.equal(
redirectUrl(ARTIFACT.url, 'doc/index.html', 'example.org', 'https://fallback'),
'https://example.org/output/job/abc/artifacts/doc/index.html',
)
assert.equal(redirectUrl(null, 'doc/index.html', 'example.org', 'https://fallback'), 'https://fallback')
})
test('statusFor', () => {
assert.deepEqual(statusFor('pending', false, 'p'), {state: 'pending', description: 'Waiting for CircleCI ...'})
assert.deepEqual(statusFor('failure', true, 'p'), {state: 'success', description: 'Link to p'})
assert.deepEqual(statusFor('success', false, 'p'), {state: 'failure', description: 'No artifacts found'})
assert.deepEqual(statusFor('success', false, 'p', 'success'), {state: 'success', description: 'No artifacts found'})
assert.equal(statusFor('success', false, 'p', 'skip'), null)
assert.deepEqual(statusFor('pending', false, 'p', 'skip'), {state: 'pending', description: 'Waiting for CircleCI ...'},
'a pending status is unaffected: nothing is known about the artifacts yet')
})
// Tier 1 fixes
test('the api token is masked and never logged', async () => {
process.env.RUNNER_DEBUG = '1' // make core.debug() actually write
let out
try {
({out} = await runAction({inputs: {'api-token': 'super-secret'}, bodies: [{items: [ARTIFACT]}]}))
} finally {
delete process.env.RUNNER_DEBUG
}
assert.ok(out.includes('::add-mask::super-secret'), 'the token is registered as a secret')
assert.ok(
!out.split('::add-mask::super-secret').join('').includes('super-secret'),
'the token appears nowhere else in the log',
)
})
test('job names are trimmed', async () => {
const {requests} = await runAction({
inputs: {'circleci-jobs': 'build_docs, docs'},
payload: {context: 'ci/circleci: docs'},
bodies: [{items: [ARTIFACT]}],
})
assert.equal(requests.length, 1, 'a name with a leading space still matches')
})
test('a status with no target_url is ignored', async () => {
const {requests, status} = await runAction({payload: {target_url: null}})
assert.deepEqual(requests, [])
assert.equal(status, null)
assert.equal(process.exitCode, 0, 'ignored, not failed')
})
test('an HTTP error fails the job with a useful message', async () => {
const {status, out} = await runAction({httpStatus: 429, bodies: [{message: 'slow down'}]})
assert.equal(status, null)
assert.equal(process.exitCode, 1) // core.setFailed()
process.exitCode = 0
assert.match(out, /::error::CircleCI API returned 429 for /)
assert.match(out, /slow down/)
})
test('fetchJson', async () => {
const okResponse = {ok: true, status: 200, json: async () => ({items: []})}
assert.deepEqual(await fetchJson(async () => okResponse, 'https://x'), {items: []})
const badResponse = {ok: false, status: 404, text: async () => 'no such project'}
await assert.rejects(
() => fetchJson(async () => badResponse, 'https://x'),
/returned 404 for https:\/\/x: no such project/,
'the status and body make it into the message',
)
// An unreadable body should not mask the status code
const unreadable = {ok: false, status: 500, text: async () => { throw new Error('nope') }}
await assert.rejects(() => fetchJson(async () => unreadable, 'https://x'), /returned 500/)
})
test('resolveStatus works without a logger', async () => {
const fetchFn = async () => ({ok: true, status: 200, json: async () => ({items: [ARTIFACT]})})
const status = await resolveStatus({
payload: {context: 'ci/circleci: build', state: 'success', target_url: 'https://circleci.com/gh/o/r/1'},
config: normalizeConfig({'artifact-path': 'doc/index.html'}),
fetchFn,
})
assert.equal(status.url, 'https://output.circle-artifacts.com/output/job/abc/artifacts/doc/index.html')
})
// CPU budget (see CLAUDE.md): the Worker gets 10 ms of CPU per request and the
// artifacts payload is ~1 MB for a large docs build, so no debug message may be
// built unless something is going to read it. A `toJSON` hook is a precise
// tripwire for that -- JSON.stringify() cannot serialize the payload without
// calling it -- where asserting on elapsed milliseconds would just be flaky.
const countingArtifacts = () => {
const payload = {items: [ARTIFACT], serialized: 0}
payload.toJSON = () => { payload.serialized++; return {items: [ARTIFACT]} }
return payload
}
const resolveWith = (artifacts, log) => resolveStatus({
payload: {context: 'ci/circleci: build', state: 'success', target_url: 'https://circleci.com/gh/o/r/1'},
config: normalizeConfig({'artifact-path': 'doc/index.html'}),
fetchFn: async () => ({ok: true, status: 200, json: async () => artifacts}),
log,
})
test('the artifacts payload is not serialized when the log discards it', async () => {
const artifacts = countingArtifacts()
await resolveWith(artifacts, () => {}) // the Worker's logger
assert.equal(artifacts.serialized, 0, 'serializing costs ~2x parsing the response')
const bare = countingArtifacts()
await resolveWith(bare) // and with no logger at all
assert.equal(bare.serialized, 0)
})
test('the chosen artifact is still named in the debug log', async () => {
const lines = []
await resolveWith(countingArtifacts(), (m) => lines.push(typeof m === 'function' ? m() : m))
assert.ok(lines.includes(`First artifact: ${ARTIFACT.url}`), 'enough to explain the link')
})
// The other half of the CPU budget: the listing is never parsed in full either.
// Serve it as a real chunked stream and count how many chunks get pulled --
// deterministic, where asserting on elapsed milliseconds would be flaky.
const chunkedListing = (count = 400, chunk = 4096) => {
const items = Array.from({length: count}, (_, i) => ({
path: `0/doc/page${i}.html`,
node_index: 0,
url: `https://output.circle-artifacts.com/output/job/abc/artifacts/0/doc/page${i}.html`,
}))
return chunkedBody(JSON.stringify({items, next_page_token: null}), chunk)
}
const chunkedBody = (text, chunk = 4096) => {
const bytes = new TextEncoder().encode(text)
let offset = 0
const state = {pulled: 0, chunks: Math.ceil(bytes.length / chunk)}
state.response = {
ok: true,
status: 200,
body: new ReadableStream({
pull(controller) {
state.pulled++
if (offset >= bytes.length) {
return controller.close()
}
controller.enqueue(bytes.slice(offset, offset + chunk))
offset += chunk
},
}),
}
return state
}
const resolveStream = (state, log) => resolveStatus({
payload: {context: 'ci/circleci: build', state: 'success', target_url: 'https://circleci.com/gh/o/r/1'},
config: normalizeConfig({'artifact-path': 'doc/index.html'}),
fetchFn: async () => state.response,
log,
})
test('the artifacts listing is not downloaded or parsed past the first entry', async () => {
const state = chunkedListing()
assert.ok(state.chunks >= 10, 'the fixture has to be big enough to stop early in')
const status = await resolveStream(state)
assert.equal(status.state, 'success')
assert.equal(status.url, 'https://output.circle-artifacts.com/output/job/abc/artifacts/doc/index.html')
assert.ok(state.pulled <= 2, `stopped after ${state.pulled} of ${state.chunks} chunks`)
})
// Cancelling is only how we stop the download early, so a stream that objects
// to being cancelled must not take the job down with it.
test('a stream that refuses to cancel still produces the status', async () => {
const state = chunkedListing()
const inner = state.response.body
state.response = {
ok: true,
status: 200,
body: new ReadableStream({
async pull(controller) {
const {done, value} = await (state.reader ??= inner.getReader()).read()
return done ? controller.close() : controller.enqueue(value)
},
cancel() { throw new Error('cancel failed') },
}),
}
const status = await resolveStream(state)
assert.equal(status.url, 'https://output.circle-artifacts.com/output/job/abc/artifacts/doc/index.html')
})
test('an empty listing still reads as no artifacts', async () => {
const state = chunkedBody(JSON.stringify({items: [], next_page_token: null}))
const status = await resolveStream(state)
assert.equal(status.state, 'failure')
assert.equal(status.description, 'No artifacts found')
assert.equal(status.url, 'https://circleci.com/gh/o/r/1', 'falls back to the job')
})
test('a malformed listing throws rather than reading as no artifacts', async () => {
await assert.rejects(() => resolveStream(chunkedBody('{"items": [truncated')), SyntaxError)
})
// A listing whose first `url` lands past the scan window must not silently come
// back empty; the scan gives up and the plain parse takes over.
test('an artifact past the scan window is still found', async () => {
const filler = 'x'.repeat(300 * 1024)
const state = chunkedBody(JSON.stringify({junk: filler, items: [ARTIFACT]}))
const status = await resolveStream(state)
assert.equal(status.state, 'success')
assert.equal(status.url, 'https://output.circle-artifacts.com/output/job/abc/artifacts/doc/index.html')
})
// JSON escapes have to survive the shortcut: the scan lifts raw bytes out of
// the response, so a path with an escape in it would come back mangled.
test('an escaped character in the artifact URL survives the scan', async () => {
// Written out rather than JSON.stringify()d, which would not emit an escape
const state = chunkedBody('{"items":[{"path":"p","url":'
+ '"https://output.circle-artifacts.com/output/job/a\\u00e9b/artifacts/0/doc/x.html"}]}')
const status = await resolveStream(state)
assert.equal(status.url, 'https://output.circle-artifacts.com/output/job/aéb/artifacts/doc/index.html')
})
test('debug() only builds an expensive message when the runner wants it', async () => {
const thunk = () => { calls++; return 'expensive' }
let calls = 0
delete process.env.RUNNER_DEBUG
let out = await captureStdout(async () => debug(thunk))
assert.equal(calls, 0, 'not built when debug logging is off')
assert.equal(out, '')
process.env.RUNNER_DEBUG = '1'
try {
out = await captureStdout(async () => {
debug(thunk)
debug('plain string')
})
} finally {
delete process.env.RUNNER_DEBUG
}
assert.equal(calls, 1)
assert.match(out, /::debug::expensive/)
assert.match(out, /::debug::plain string/)
})
test('debug() passes plain strings through whatever the runner is doing', async () => {
const out = await captureStdout(async () => debug('always emitted'))
assert.match(out, /::debug::always emitted/, 'core.debug decides, as it always did')
})
test('post-pending: false skips the pending status entirely', async () => {
const {requests, url, status} = await runAction({
inputs: {'post-pending': 'false'},
payload: {state: 'pending'},
})
assert.deepEqual(requests, [], 'and costs no CircleCI call')
assert.equal(url, undefined)
assert.equal(status, null)
})
test('post-pending defaults to on, and only "false" turns it off', async () => {
for (const [value, expected] of [[undefined, 'pending'], ['true', 'pending'], ['False', null], ['false', null]]) {
const {status} = await runAction({
inputs: value === undefined ? {} : {'post-pending': value},
payload: {state: 'pending'},
bodies: [{items: []}],
})
assert.equal(status === null ? null : status.state, expected, `post-pending: ${value}`)
}
})
// A job that uploads nothing is red by default, but it is an expected outcome
// for a repo that skips its CircleCI build on demand (scipy's "[skip circle]")
test('no-artifact-state: success links to the job in green instead', async () => {
const {url, status} = await runAction({
inputs: {'no-artifact-state': 'success'},
bodies: [{items: []}],
})
assert.equal(url, 'https://circleci.com/gh/scientific-python/circleci-artifacts-redirector-action/94')
assert.equal(status.state, 'success')
assert.equal(status.description, 'No artifacts found')
assert.equal(status.target_url, url, 'still points at the job, not a link that 404s')
})
test('no-artifact-state: skip posts nothing at all', async () => {
const {url, status} = await runAction({
inputs: {'no-artifact-state': 'SKIP'}, // and the value is case-insensitive
bodies: [{items: []}],
})
assert.equal(status, null)
assert.equal(url, undefined, 'and there is no artifact URL to output either')
assert.equal(process.exitCode, 0, 'ignored, not failed')
})
test('no-artifact-state only applies when there are no artifacts', async () => {
for (const value of ['success', 'skip']) {
const {status} = await runAction({inputs: {'no-artifact-state': value}, bodies: [{items: [ARTIFACT]}]})
assert.equal(status.description, 'Link to doc/index.html', `no-artifact-state: ${value}`)
}
})
test('an unknown no-artifact-state fails the job rather than guessing', async () => {
const {status, out} = await runAction({inputs: {'no-artifact-state': 'neutral'}, bodies: [{items: []}]})
assert.equal(status, null)
assert.equal(process.exitCode, 1) // core.setFailed()
process.exitCode = 0
assert.match(out, /::error::no-artifact-state must be one of failure, success, skip, got 'neutral'/)
})