/
laverna.spec.js
932 lines (855 loc) · 20.8 KB
/
laverna.spec.js
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
/**
* This tests the `publish` script.
*
* `memfs` is used to mock the filesystem.
*
* @packageDocumentation
* @see {@link https://npm.im/memfs}
*/
const kleur = require('kleur')
const crypto = require('node:crypto')
const { glob: realGlob } = require('glob')
const { EventEmitter } = require('node:events')
// eslint-disable-next-line ava/use-test
const { default: anyTest } = require('ava')
const { memfs, fs } = require('memfs')
const { Laverna } = require('../src')
const { mock } = require('node:test')
/**
* Test context object for our tests
*
* @typedef PublishTestContext
* @property {{ error: import('node:test').Mock<Console['error']> }} console
* @property {import('node:test').Mock<import('../src').SpawnFn>} spawn
* @property {(
* opts?: import('../src').LavernaOptions,
* caps?: import('../src').LavernaCapabilities
* ) => Promise<void>} runLaverna
* @property {(
* pkgNames: string[],
* opts?: import('../src').LavernaOptions,
* caps?: import('../src').LavernaCapabilities
* ) => Promise<void>} runInvokePublish
*/
/**
* This just tells `ava` we're using {@link PublishTestContext} for the context.
*/
const test = /** @type {import('ava').TestFn<PublishTestContext>} */ (anyTest)
/**
* A valid `package.json` for the root workspace used in many tests
*/
const DEFAULT_ROOT_PKG_JSON = JSON.stringify({
name: 'root',
version: '1.0.0',
workspaces: ['packages/*'],
})
/**
* Random pkg name used to test new package detection
*
* @returns {string} A random package name
*/
function getRandomPkgName() {
return crypto.randomBytes(32).toString('hex')
}
/**
* Base options for {@link Laverna}, providing some stubs.
*/
const BASE_OPTS = Object.freeze(
/** @type {import('../src').LavernaOptions} */ ({
/**
* Because the root of the phony `memfs` filesystem is `/`, we use it here.
*/
root: '/', // we use this as the custom memfs fs root
/**
* Force dry-run
*/
dryRun: true,
/**
* Never prompt for confirmation in these tests
*/
yes: true,
})
)
/**
* Base capabilities for {@link Laverna}, providing some stubs.
*/
const BASE_CAPS = Object.freeze(
/** @type {import('../src').LavernaCapabilities} */ ({
/**
* The phony `fs` is given to `glob`--it supports a custom `fs` module--so
* it can find files in there.
*/
glob: realGlob,
/**
* Node.js' `exec` returns more than Laverna needs; this will work for our
* purposes
*/
execFile: async () => ({ stdout: '', stderr: '' }),
/**
* The phony filesystem provided by `memfs`.
*
* Tests should create their own; this is just defensive.
*/
fs,
})
)
test.before(() => {
// this disables ANSI escapes in output for easier comparison
kleur.enabled = false
})
test.beforeEach((t) => {
/**
* This is passed to {@link Laverna} as a capability.
*/
const console = {
error: mock.fn(
/** @type {(message?: any, ...optionalParams: any[]) => void} */ (
() => {}
)
),
}
/**
* Mock `spawn` fn
*
* The default behavior is to immediately emit an `exit` event with a `0` exit
* code.
*
* This is passed to {@link Laverna} as a capability.
*/
const spawn = mock.fn(
/**
* @param {string} cmd
* @param {string[]} args
* @param {import('node:child_process').SpawnOptions} opts
* @returns {import('node:events').EventEmitter}
*/
// eslint-disable-next-line no-unused-vars
(cmd, args, opts) => {
const ee = new EventEmitter()
setImmediate(() => {
ee.emit('exit', 0)
})
return ee
}
)
/**
* Helps run {@link Laverna.invokePublish} with a custom set of options and
* caps.
*
* Provides the default {@link ConsoleSpy} and {@link SpawnSpy} implementations
* if not overridden by the test.
*
* Does not create a child process
*
* @param {string[]} pkgNames
* @param {import('../src').LavernaOptions} opts
* @param {import('../src').LavernaCapabilities} caps
* @returns {Promise<void>}
*/
const runInvokePublish = async (pkgNames, opts = {}, caps = {}) => {
opts = { ...BASE_OPTS, ...opts }
t.true(opts.dryRun, 'dryRun must be true for tests')
const laverna = new Laverna(opts, {
...BASE_CAPS,
console: console,
spawn: spawn,
...caps,
})
await laverna.invokePublish(pkgNames)
}
/**
* Helps run {@link Laverna.publishWorkspaces} with a custom set of options and
* caps
*
* Provides the default {@link ConsoleSpy} and {@link SpawnSpy} implementations
* if not overridden by the test.
*
* Does not create a child process
*
* @param {import('../src').LavernaOptions} opts
* @param {import('../src').LavernaCapabilities} caps
* @returns {Promise<void>}
*/
const runLaverna = async (opts = {}, caps = {}) => {
opts = { ...BASE_OPTS, ...opts }
t.true(opts.dryRun, 'dryRun must be true for tests')
const laverna = new Laverna(opts, {
...BASE_CAPS,
console,
spawn,
...caps,
})
await laverna.publishWorkspaces()
}
t.context = {
console,
spawn,
runLaverna,
runInvokePublish,
}
})
test('publishWorkspaces - no root package.json', async (t) => {
await t.throwsAsync(t.context.runLaverna(), {
message: /Could not read package.json in workspace root/,
})
})
test('publishWorkspaces - no workspaces', async (t) => {
const { fs } = memfs({
'/': {
'package.json': JSON.stringify({ name: 'root', version: '1.0.0' }),
},
})
await t.throwsAsync(t.context.runLaverna({}, { fs }), {
message: /No "workspaces" prop found/,
})
})
test('publishWorkspaces - invalid root package.json', async (t) => {
const { fs } = memfs({
'/': {
'package.json': 'not json',
},
})
await t.throwsAsync(t.context.runLaverna({}, { fs }), {
instanceOf: SyntaxError,
})
})
test('publishWorkspaces - glob failure', async (t) => {
const { fs } = memfs({
'/': {
'package.json': JSON.stringify({
name: 'root',
version: '1.0.0',
workspaces: ['/somewhere/over/the/rainbow/*'],
}),
},
})
const err = new Error('glob failed')
await t.throwsAsync(
t.context.runLaverna(
{},
{
fs,
glob: async () => {
throw err
},
}
),
{ is: err }
)
})
test('publishWorkspaces - invalid workspaces - not array', async (t) => {
const { fs } = memfs({
'/': {
'package.json': JSON.stringify({
name: 'root',
version: '1.0.0',
workspaces: '/somewhere/over/the/rainbow/*',
}),
},
})
await t.throwsAsync(t.context.runLaverna({}, { fs }), {
message: /"workspaces" prop in .+ is invalid; must be array of strings/,
})
})
test('publishWorkspaces - invalid workspaces - not strings', async (t) => {
const { fs } = memfs({
'/': {
'package.json': JSON.stringify({
name: 'root',
version: '1.0.0',
workspaces: [true, false, 1],
}),
},
})
await t.throwsAsync(t.context.runLaverna({}, { fs }), {
message: /"workspaces" prop in .+ is invalid; must be array of strings/,
})
})
test('publishWorkspaces - invalid JSON error from `npm view`', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'workspace1',
version: '1.0.0',
}),
},
},
},
})
await t.throwsAsync(
t.context.runLaverna(
{},
{
fs,
execFile: async () => {
return { stdout: 'not json', stderr: '' }
},
}
),
{
instanceOf: SyntaxError,
}
)
})
test('publishWorkspaces - `npm view` returns a single version', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'workspace1',
version: '1.0.0',
}),
},
},
},
})
await t.notThrowsAsync(
t.context.runLaverna(
{},
{
fs,
execFile: async () => {
return { stdout: '"0.0.1"', stderr: '' }
},
}
)
)
const args = t.context.console.error.mock.calls.flatMap(
(call) => call.arguments
)
t.true(
args.some((arg) =>
`${arg}`.includes('These package(s) will be published:\nworkspace1@1.0.0')
)
)
})
test('publish workspaces - unexpected JSON parsed from npm view', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'workspace1',
version: '1.0.0',
}),
},
},
},
})
await t.throwsAsync(
t.context.runLaverna(
{},
{
fs,
execFile: async () => ({
stdout: JSON.stringify({ poppies: 'fritz' }),
stderr: '',
}),
}
),
{
instanceOf: TypeError,
message: /was not a JSON array of strings/,
}
)
})
test('publishWorkspaces - unexpected error from npm view', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'workspace1',
version: '1.0.0',
}),
},
},
},
})
const err = new Error('poppies & fritz')
await t.throwsAsync(
t.context.runLaverna(
{},
{
fs,
execFile: async () => {
throw err
},
}
),
{
is: err,
}
)
})
test('publishWorkspaces - non-matching glob pattern', async (t) => {
const { fs } = memfs({
'/': {
'package.json': JSON.stringify({
name: 'root',
version: '1.0.0',
workspaces: ['/somewhere/over/the/rainbow/*'],
}),
},
})
await t.throwsAsync(t.context.runLaverna({}, { fs }), {
message: /"workspaces" pattern .+ matched no files\/dirs:/,
})
})
test('publishWorkspaces - empty workspace dir', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
package1: {},
},
},
})
await t.context.runLaverna({}, { fs })
const args = t.context.console.error.mock.calls.flatMap(
(call) => call.arguments
)
t.true(
args.some((arg) =>
/Workspace dir .+ contains no `package\.json`/.test(`${arg}`)
)
)
})
test('publishWorkspaces - other read failure', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': '{}',
},
},
},
})
const err = new Error('read failed')
await t.throwsAsync(
t.context.runLaverna(
{},
{
/**
* This hacks the phony `fs` with a phonier `readFile` which fails if we
* ask it to get the package.json for workspace1, as defined above
*/
fs: {
...fs,
promises: {
...fs.promises,
// starting to want sinon about now
readFile: (filename) => {
if (filename === '/packages/workspace1/package.json') {
return Promise.reject(err)
}
return fs.promises.readFile(filename)
},
},
},
}
),
{ is: err }
)
})
test('publishWorkspaces - unparseable workspace package.json', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
// "oops" is literally the content of package.json
'package.json': 'oops',
},
},
},
})
await t.throwsAsync(t.context.runLaverna({}, { fs }), {
instanceOf: SyntaxError,
})
})
test('publishWorkspaces - private package', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'workspace1',
version: '1.0.0',
private: true,
}),
},
},
},
})
await t.context.runLaverna({}, { fs })
const args = t.context.console.error.mock.calls.flatMap(
(call) => call.arguments
)
t.true(args.some((arg) => `${arg}`.includes('Skipping private package')))
})
test('publishWorkspaces - nothing to publish', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'workspace1',
version: '1.0.0',
private: true,
}),
},
},
},
})
await t.context.runLaverna({}, { fs })
const args = t.context.console.error.mock.calls.flatMap(
(call) => call.arguments
)
t.true(args.some((arg) => `${arg}`.includes('Nothing to publish')))
})
test('publishWorkspaces - missing workspace package version', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'workspace1',
}),
},
},
},
})
await t.throwsAsync(
t.context.runLaverna(
{},
{
fs,
}
),
{
message:
'Missing package name and/or version in ./packages/workspace1/package.json; cannot be published',
}
)
})
test('publishWorkspaces - missing workspace package name', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
version: '1.0.0',
}),
},
},
},
})
await t.throwsAsync(
t.context.runLaverna(
{},
{
fs,
}
),
{
message:
'Missing package name and/or version in ./packages/workspace1/package.json; cannot be published',
}
)
})
test('publishWorkspaces - unknown package', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'super-not-real',
version: '1.0.0',
}),
},
},
},
})
await t.throwsAsync(
t.context.runLaverna(
{},
{
fs,
execFile: async () => {
// the error thrown here must have a json-parseable `stdout` prop
throw Object.assign(new Error('stuff & things'), {
stdout: JSON.stringify({
error: {
code: 'fkdj',
summary: 'stuff & things',
detail: 'mind yr own biz',
},
}),
})
},
}
),
{
message: /Querying for package.+failed/,
}
)
})
test('publishWorkspaces - cannot find npm', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'super-not-real',
version: '1.0.0',
}),
},
},
},
})
await t.throwsAsync(
t.context.runLaverna(
{},
{
fs,
execFile: async () => {
throw Object.assign(new Error('no npm here'), { code: 'ENOENT' })
},
}
),
{
message: /Could not find npm:/,
}
)
})
test('publishWorkspaces - new package', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'super-not-real',
version: '1.0.0',
}),
},
},
},
})
await t.context.runLaverna(
{ newPkg: ['super-not-real'] },
{
fs,
/**
* The error thrown here is tossed out, because if `npm view` would throw,
* Laverna checks `newPkg` for the package name, and if it's there, no
* error is thrown.
*/
execFile: async () => {
throw new Error()
},
}
)
const args = t.context.console.error.mock.calls.flatMap(
(call) => call.arguments
)
t.true(
args.some((arg) =>
`${arg}`.includes(`Package super-not-real confirmed as new`)
)
)
})
test('publishWorkspaces - known package - unparseable JSON', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'lavamoat',
version: '1.0.6', // first published version
}),
},
},
},
})
await t.throwsAsync(
t.context.runLaverna(
{},
{
fs,
execFile: async () => ({ stdout: 'not json', stderr: '' }),
}
),
{ instanceOf: SyntaxError }
)
})
test('publishWorkspaces - known package - existing version', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'lavamoat',
version: '1.0.6', // first published version
}),
},
},
},
})
// uses real `npm view`
await t.context.runLaverna(
{},
{
fs,
// alternatively, we could override exec as in the other tests. this is higher-level.
// it just says that "version 1.0.6 of lavamoat has already been published"
getVersionsFactory: () => async () => ['1.0.6'],
}
)
const args = t.context.console.error.mock.calls.flatMap(
(call) => call.arguments
)
t.true(args.some((arg) => `${arg}`.includes('Nothing to publish')))
})
test('publishWorkspaces - known packages - new versions', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'lavamoat',
version: '31337.42.9000', // this doesn't scale
}),
},
workspace2: {
'package.json': JSON.stringify({
name: 'lavamoat-tofu',
version: '9000.31337.42',
}),
},
},
},
})
await t.context.runLaverna(
{},
{ fs, getVersionsFactory: () => async () => ['1.0.6'] }
)
const args = t.context.console.error.mock.calls.flatMap(
(call) => call.arguments
)
t.true(
args.some((arg) =>
`${arg}`.includes(
'These package(s) will be published:\nlavamoat-tofu@9000.31337.42\nlavamoat@31337.42.9000'
)
)
)
})
test('publishWorkspaces - known packages - duplicate package names', async (t) => {
const { fs } = memfs({
'/': {
'package.json': DEFAULT_ROOT_PKG_JSON,
packages: {
workspace1: {
'package.json': JSON.stringify({
name: 'lavamoat',
version: '31337.42.9000', // this doesn't scale
}),
},
workspace2: {
'package.json': JSON.stringify({
name: 'lavamoat',
version: '9000.31337.42',
}),
},
},
},
})
// uses real `npm view`
await t.throwsAsync(
t.context.runLaverna(
{},
{
fs,
getVersionsFactory: () => async () => ['1.0.6'],
}
),
{ message: `Duplicate package name(s) found in workspaces: lavamoat` }
)
})
test('invokePublish - basic usage', async (t) => {
const pkgName = getRandomPkgName()
await t.context.runInvokePublish([pkgName])
t.deepEqual(t.context.spawn.mock.calls[0].arguments, [
'npm',
['publish', `--workspace=${pkgName}`, '--dry-run'],
{ stdio: 'inherit', cwd: '/', shell: true },
])
})
test('invokePublish - dry run', async (t) => {
await t.context.runInvokePublish(['foo'])
t.deepEqual(t.context.spawn.mock.calls[0].arguments, [
'npm',
['publish', `--workspace=foo`, '--dry-run'],
{ stdio: 'inherit', cwd: '/', shell: true },
])
})
test('invokePublish - nonzero exit code', async (t) => {
await t.throwsAsync(
t.context.runInvokePublish(
['foo'],
{},
{
spawn: mock.fn(() => {
const ee = new EventEmitter()
setImmediate(() => {
ee.emit('exit', 1)
})
return ee
}),
}
),
{
message: 'npm publish exited with code 1',
}
)
})
test('invokePublish - other error', async (t) => {
const err = new Error('help meeeee')
await t.throwsAsync(
t.context.runInvokePublish(
['foo'],
{},
{
spawn: mock.fn(() => {
const ee = new EventEmitter()
setImmediate(() => {
ee.emit('error', err)
})
return ee
}),
}
),
{
is: err,
}
)
})