-
-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathatom-environment-spec.js
More file actions
974 lines (844 loc) · 33 KB
/
Copy pathatom-environment-spec.js
File metadata and controls
974 lines (844 loc) · 33 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
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
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
const { conditionPromise } = require('./helpers/async-spec-helpers');
const fs = require('fs');
const path = require('path');
const temp = require('temp').track();
const AtomEnvironment = require('../src/atom-environment');
const { timeoutPromise: wait } = require('./helpers/async-spec-helpers');
describe('AtomEnvironment', () => {
describe('window sizing methods', () => {
describe('::getPosition and ::setPosition', () => {
let originalPosition = null;
beforeEach(() => (originalPosition = atom.getPosition()));
afterEach(() => atom.setPosition(originalPosition.x, originalPosition.y));
it('sets the position of the window, and can retrieve the position just set', () => {
atom.setPosition(22, 45);
expect(atom.getPosition()).toEqual({ x: 22, y: 45 });
});
});
describe('::getSize and ::setSize', () => {
let originalSize = null;
beforeEach(() => (originalSize = atom.getSize()));
afterEach(async () => {
atom.setSize(originalSize.width, originalSize.height);
});
it('sets the size of the window, and can retrieve the size just set', async () => {
const newWidth = originalSize.width - 12;
const newHeight = originalSize.height - 23;
atom.setSize(newWidth, newHeight);
expect(atom.getSize()).toEqual({ width: newWidth, height: newHeight });
});
});
});
describe('.isReleasedVersion()', () => {
it('returns false if the version is a SHA and true otherwise', () => {
let version = '0.1.0';
spyOn(atom, 'getVersion').and.callFake(() => version);
expect(atom.isReleasedVersion()).toBe(true);
version = '36b5518';
expect(atom.isReleasedVersion()).toBe(false);
});
});
describe('.versionSatisfies()', () => {
it('returns appropriately for provided range', () => {
let testPulsarVersion = '0.1.0';
spyOn(atom, 'getVersion').and.callFake(() => testPulsarVersion);
expect(atom.versionSatisfies('>0.2.0')).toBe(false);
expect(atom.versionSatisfies('>=0.x.x <=2.x.x')).toBe(true);
expect(atom.versionSatisfies('^0.1.x')).toBe(true);
});
});
describe('loading default config', () => {
it('loads the default core config schema', () => {
expect(atom.config.get('core.excludeVcsIgnoredPaths')).toBe(true);
expect(atom.config.get('core.followSymlinks')).toBe(true);
expect(atom.config.get('editor.showInvisibles')).toBe(false);
});
});
describe('window onerror handler', () => {
let devToolsPromise = null;
beforeEach(() => {
devToolsPromise = Promise.resolve();
spyOn(atom, 'openDevTools').and.returnValue(devToolsPromise);
spyOn(atom, 'executeJavaScriptInDevTools');
});
it('will open the dev tools when an error is triggered', async () => {
try {
a + 1; // eslint-disable-line no-undef, no-unused-expressions
} catch (e) {
window.onerror(e.toString(), 'abc', 2, 3, e);
}
await devToolsPromise;
expect(atom.openDevTools).toHaveBeenCalled();
expect(atom.executeJavaScriptInDevTools).toHaveBeenCalled();
});
describe('::onWillThrowError', () => {
let willThrowSpy = null;
beforeEach(() => {
willThrowSpy = jasmine.createSpy();
});
it('is called when there is an error', () => {
let error = null;
atom.onWillThrowError(willThrowSpy);
try {
a + 1; // eslint-disable-line no-undef, no-unused-expressions
} catch (e) {
error = e;
window.onerror(e.toString(), 'abc', 2, 3, e);
}
delete willThrowSpy.calls.mostRecent().args[0].preventDefault;
expect(willThrowSpy).toHaveBeenCalledWith({
message: error.toString(),
url: 'abc',
line: 2,
column: 3,
originalError: error
});
});
it('will not show the devtools when preventDefault() is called', () => {
willThrowSpy.and.callFake(errorObject => errorObject.preventDefault());
atom.onWillThrowError(willThrowSpy);
try {
a + 1; // eslint-disable-line no-undef, no-unused-expressions
} catch (e) {
window.onerror(e.toString(), 'abc', 2, 3, e);
}
expect(willThrowSpy).toHaveBeenCalled();
expect(atom.openDevTools).not.toHaveBeenCalled();
expect(atom.executeJavaScriptInDevTools).not.toHaveBeenCalled();
});
});
describe('::onDidThrowError', () => {
let didThrowSpy = null;
beforeEach(() => (didThrowSpy = jasmine.createSpy()));
it('is called when there is an error', () => {
let error = null;
atom.onDidThrowError(didThrowSpy);
try {
a + 1; // eslint-disable-line no-undef, no-unused-expressions
} catch (e) {
error = e;
window.onerror(e.toString(), 'abc', 2, 3, e);
}
expect(didThrowSpy).toHaveBeenCalledWith({
message: error.toString(),
url: 'abc',
line: 2,
column: 3,
originalError: error
});
});
});
});
describe('.assert(condition, message, callback)', () => {
let errors = null;
beforeEach(() => {
errors = [];
spyOn(atom, 'isReleasedVersion').and.returnValue(true);
atom.onDidFailAssertion(error => errors.push(error));
});
describe('if the condition is false', () => {
it('notifies onDidFailAssertion handlers with an error object based on the call site of the assertion', () => {
const result = atom.assert(false, 'a == b');
expect(result).toBe(false);
expect(errors.length).toBe(1);
expect(errors[0].message).toBe('Assertion failed: a == b');
expect(errors[0].stack).toContain('atom-environment-spec');
});
describe('if passed a callback function', () => {
it("calls the callback with the assertion failure's error object", () => {
let error = null;
atom.assert(false, 'a == b', e => (error = e));
expect(error).toBe(errors[0]);
});
});
describe('if passed metadata', () => {
it("assigns the metadata on the assertion failure's error object", () => {
atom.assert(false, 'a == b', { foo: 'bar' });
expect(errors[0].metadata).toEqual({ foo: 'bar' });
});
});
describe('when Atom has been built from source', () => {
it('throws an error', () => {
atom.isReleasedVersion.and.returnValue(false);
expect(() => atom.assert(false, 'testing')).toThrowError(
'Assertion failed: testing'
);
});
});
});
describe('if the condition is true', () => {
it('does nothing', () => {
const result = atom.assert(true, 'a == b');
expect(result).toBe(true);
expect(errors).toEqual([]);
});
});
});
describe('saving and loading', () => {
beforeEach(() => {
jasmine.useRealClock();
atom.enablePersistence = true;
});
afterEach(() => {
atom.enablePersistence = false;
});
it('selects the state based on the current project paths', async () => {
jasmine.useRealClock();
const [dir1, dir2] = [temp.mkdirSync('dir1-'), temp.mkdirSync('dir2-')];
const loadSettings = Object.assign(atom.getLoadSettings(), {
initialProjectRoots: [dir1],
windowState: null
});
spyOn(atom, 'getLoadSettings').and.callFake(() => loadSettings);
spyOn(atom, 'serialize').and.returnValue({ stuff: 'cool' });
atom.project.setPaths([dir1, dir2]);
// State persistence will fail if other Atom instances are running
expect(await atom.stateStore.connect()).toBe(true);
await atom.saveState();
expect(await atom.loadState()).toBeFalsy();
loadSettings.initialProjectRoots = [dir2, dir1];
expect(await atom.loadState()).toEqual({ stuff: 'cool' });
});
it('saves state when the CPU is idle after a keydown or mousedown event', async () => {
jasmine.useRealClock();
const atomEnv = new AtomEnvironment({
applicationDelegate: global.atom.applicationDelegate
});
const idleCallbacks = [];
atomEnv.initialize({
window: {
requestIdleCallback(callback) {
idleCallbacks.push(callback);
},
addEventListener() {},
removeEventListener() {}
},
document: document.implementation.createHTMLDocument()
});
spyOn(atomEnv, 'saveState');
const keydown = new KeyboardEvent('keydown');
atomEnv.document.dispatchEvent(keydown);
await wait(atomEnv.saveStateDebounceInterval);
idleCallbacks.shift()?.();
expect(atomEnv.saveState).toHaveBeenCalledWith({ isUnloading: false });
expect(atomEnv.saveState).not.toHaveBeenCalledWith({ isUnloading: true });
atomEnv.saveState.calls.reset();
const mousedown = new MouseEvent('mousedown');
atomEnv.document.dispatchEvent(mousedown);
await wait(atomEnv.saveStateDebounceInterval);
idleCallbacks.shift()?.();
expect(atomEnv.saveState).toHaveBeenCalledWith({ isUnloading: false });
expect(atomEnv.saveState).not.toHaveBeenCalledWith({ isUnloading: true });
atomEnv.destroy();
});
it('ignores mousedown/keydown events happening after calling prepareToUnloadEditorWindow', async () => {
const atomEnv = new AtomEnvironment({
applicationDelegate: global.atom.applicationDelegate
});
const idleCallbacks = [];
atomEnv.initialize({
window: {
requestIdleCallback(callback) {
idleCallbacks.push(callback);
},
addEventListener() {},
removeEventListener() {}
},
document: document.implementation.createHTMLDocument()
});
spyOn(atomEnv, 'saveState');
let mousedown = new MouseEvent('mousedown');
atomEnv.document.dispatchEvent(mousedown);
expect(atomEnv.saveState).not.toHaveBeenCalled();
await atomEnv.prepareToUnloadEditorWindow();
expect(atomEnv.saveState).toHaveBeenCalledWith({ isUnloading: true });
await wait(atomEnv.saveStateDebounceInterval);
idleCallbacks.shift()();
expect(atomEnv.saveState.calls.count()).toBe(1);
mousedown = new MouseEvent('mousedown');
atomEnv.document.dispatchEvent(mousedown);
await wait(atomEnv.saveStateDebounceInterval);
idleCallbacks.shift()();
expect(atomEnv.saveState.calls.count()).toBe(1);
atomEnv.destroy();
});
it('serializes the project state with all the options supplied in saveState', async () => {
spyOn(atom.project, 'serialize').and.returnValue({ foo: 42 });
await atom.saveState({ anyOption: 'any option' });
expect(atom.project.serialize.calls.count()).toBe(1);
expect(atom.project.serialize.calls.mostRecent().args[0]).toEqual({
anyOption: 'any option'
});
});
it('serializes the text editor registry', async () => {
await atom.packages.activatePackage('language-text');
const editor = await atom.workspace.open('sample.js');
expect(atom.grammars.assignLanguageMode(editor, 'text.plain')).toBe(true);
const atom2 = new AtomEnvironment({
applicationDelegate: atom.applicationDelegate,
window: document.createElement('div'),
document: Object.assign(document.createElement('div'), {
body: document.createElement('div'),
head: document.createElement('div')
})
});
atom2.initialize({ document, window });
await atom2.deserialize(atom.serialize());
await atom2.packages.activatePackage('language-text');
const editor2 = atom2.workspace.getActiveTextEditor();
expect(
editor2
.getBuffer()
.getLanguageMode()
.getLanguageId()
).toBe('text.plain');
atom2.destroy();
});
describe('deserialization failures', () => {
it('propagates unrecognized project state restoration failures', async () => {
let err;
spyOn(atom.project, 'deserialize').and.callFake(() => {
err = new Error('deserialization failure');
return Promise.reject(err);
});
spyOn(atom.notifications, 'addError');
await atom.deserialize({ project: 'should work' });
expect(atom.notifications.addError).toHaveBeenCalledWith(
'Unable to deserialize project',
{
description: 'deserialization failure',
stack: err.stack
}
);
});
it('disregards missing project folder errors', async () => {
spyOn(atom.project, 'deserialize').and.callFake(() => {
const err = new Error('deserialization failure');
err.missingProjectPaths = ['nah'];
return Promise.reject(err);
});
spyOn(atom.notifications, 'addError');
await atom.deserialize({ project: 'should work' });
expect(atom.notifications.addError).not.toHaveBeenCalled();
});
});
});
describe('openInitialEmptyEditorIfNecessary', () => {
describe('when there are no paths set', () => {
beforeEach(() =>
spyOn(atom, 'getLoadSettings').and.returnValue({ hasOpenFiles: false })
);
it('opens an empty buffer', () => {
spyOn(atom.workspace, 'open');
atom.openInitialEmptyEditorIfNecessary();
expect(atom.workspace.open).toHaveBeenCalledWith(null, {
pending: true
});
});
it('does not open an empty buffer when a buffer is already open', async () => {
await atom.workspace.open();
spyOn(atom.workspace, 'open');
atom.openInitialEmptyEditorIfNecessary();
expect(atom.workspace.open).not.toHaveBeenCalled();
});
it('does not open an empty buffer when core.openEmptyEditorOnStart is false', () => {
atom.config.set('core.openEmptyEditorOnStart', false);
spyOn(atom.workspace, 'open');
atom.openInitialEmptyEditorIfNecessary();
expect(atom.workspace.open).not.toHaveBeenCalled();
});
});
describe('when the project has a path', () => {
beforeEach(() => {
spyOn(atom, 'getLoadSettings').and.returnValue({ hasOpenFiles: true });
spyOn(atom.workspace, 'open');
});
it('does not open an empty buffer', () => {
atom.openInitialEmptyEditorIfNecessary();
expect(atom.workspace.open).not.toHaveBeenCalled();
});
});
});
describe('adding a project folder', () => {
it('does nothing if the user dismisses the file picker', () => {
const projectRoots = atom.project.getPaths();
spyOn(atom, 'pickFolder').and.callFake(callback => callback(null));
atom.addProjectFolder();
expect(atom.project.getPaths()).toEqual(projectRoots);
});
describe('when there is no saved state for the added folders', () => {
beforeEach(() => {
spyOn(atom, 'loadState').and.returnValue(Promise.resolve(null));
spyOn(atom, 'attemptRestoreProjectStateForPaths');
});
it('adds the selected folder to the project', async () => {
atom.project.setPaths([]);
const tempDirectory = temp.mkdirSync('a-new-directory');
spyOn(atom, 'pickFolder').and.callFake(callback =>
callback([tempDirectory])
);
await atom.addProjectFolder();
expect(atom.project.getPaths()).toEqual([tempDirectory]);
expect(atom.attemptRestoreProjectStateForPaths).not.toHaveBeenCalled();
});
});
describe('when there is saved state for the relevant directories', () => {
const state = Symbol('savedState');
beforeEach(() => {
spyOn(atom, 'getStateKey').and.callFake(dirs => dirs.join(':'));
spyOn(atom, 'loadState').and.callFake((key) => key === __dirname ? state : null);
spyOn(atom, 'attemptRestoreProjectStateForPaths');
spyOn(atom, 'pickFolder').and.callFake(callback =>
callback([__dirname])
);
atom.project.setPaths([]);
});
describe('when there are no project folders', () => {
it('attempts to restore the project state', async () => {
await atom.addProjectFolder();
expect(atom.attemptRestoreProjectStateForPaths).toHaveBeenCalledWith(
state,
[__dirname]
);
expect(atom.project.getPaths()).toEqual([]);
});
});
describe('when there are already project folders', () => {
const openedPath = path.join(__dirname, 'fixtures');
beforeEach(() => atom.project.setPaths([openedPath]));
it('does not attempt to restore the project state, instead adding the project paths', async () => {
await atom.addProjectFolder();
expect(
atom.attemptRestoreProjectStateForPaths
).not.toHaveBeenCalled();
expect(atom.project.getPaths()).toEqual([openedPath, __dirname]);
});
});
});
});
describe('attemptRestoreProjectStateForPaths(state, projectPaths, filesToOpen)', () => {
describe('when the window is clean (empty or has only unnamed, unmodified buffers)', () => {
beforeEach(async () => {
// Unnamed, unmodified buffer doesn't count toward "clean"-ness
await atom.workspace.open();
});
it('automatically restores the saved state into the current environment', async () => {
const projectPath = temp.mkdirSync();
const filePath1 = path.join(projectPath, 'file-1');
const filePath2 = path.join(projectPath, 'file-2');
const filePath3 = path.join(projectPath, 'file-3');
fs.writeFileSync(filePath1, 'abc');
fs.writeFileSync(filePath2, 'def');
fs.writeFileSync(filePath3, 'ghi');
const env1 = new AtomEnvironment({
applicationDelegate: atom.applicationDelegate
});
env1.project.setPaths([projectPath]);
await env1.workspace.open(filePath1);
await env1.workspace.open(filePath2);
await env1.workspace.open(filePath3);
const env1State = env1.serialize();
env1.destroy();
const env2 = new AtomEnvironment({
applicationDelegate: atom.applicationDelegate
});
await env2.attemptRestoreProjectStateForPaths(
env1State,
[projectPath],
[filePath2]
);
const restoredURIs = env2.workspace.getPaneItems().map(p => p.getURI());
expect(restoredURIs).toEqual([filePath1, filePath2, filePath3]);
env2.destroy();
});
describe('when a dock has a non-text editor', () => {
it("doesn't prompt the user to restore state", () => {
const dock = atom.workspace.getLeftDock();
dock.getActivePane().addItem({
getTitle() {
return 'title';
},
element: document.createElement('div')
});
const state = {};
spyOn(atom, 'confirm');
atom.attemptRestoreProjectStateForPaths(
state,
[__dirname],
[__filename]
);
expect(atom.confirm).not.toHaveBeenCalled();
});
});
});
describe('when the window is dirty', () => {
let editor;
beforeEach(async () => {
editor = await atom.workspace.open();
editor.setText('new editor');
});
describe('when a dock has a modified editor', () => {
it('prompts the user to restore the state', () => {
const dock = atom.workspace.getLeftDock();
dock.getActivePane().addItem(editor);
spyOn(atom, 'confirm').and.returnValue(1);
spyOn(atom.project, 'addPath');
spyOn(atom.workspace, 'open');
const state = Symbol('state');
atom.attemptRestoreProjectStateForPaths(
state,
[__dirname],
[__filename]
);
expect(atom.confirm).toHaveBeenCalled();
});
});
it('prompts the user to restore the state in a new window, discarding it and adding folder to current window', async () => {
jasmine.useRealClock();
spyOn(atom, 'confirm').and.callFake((options, callback) => callback(1));
spyOn(atom.project, 'addPaths');
spyOn(atom.workspace, 'open');
const state = Symbol('state');
atom.attemptRestoreProjectStateForPaths(
state,
[__dirname],
[__filename]
);
expect(atom.confirm).toHaveBeenCalled();
await conditionPromise(() => atom.project.addPaths.calls.count() === 1);
expect(atom.project.addPaths).toHaveBeenCalledWith([__dirname]);
expect(atom.workspace.open.calls.count()).toBe(1);
expect(atom.workspace.open).toHaveBeenCalledWith(__filename);
});
it('prompts the user to restore the state in a new window, opening a new window', async () => {
jasmine.useRealClock();
spyOn(atom, 'confirm').and.callFake((options, callback) => callback(0));
spyOn(atom, 'open');
const state = Symbol('state');
atom.attemptRestoreProjectStateForPaths(
state,
[__dirname],
[__filename]
);
expect(atom.confirm).toHaveBeenCalled();
await conditionPromise(() => atom.open.calls.count() === 1);
expect(atom.open).toHaveBeenCalledWith({
pathsToOpen: [__dirname, __filename],
newWindow: true,
devMode: atom.inDevMode(),
safeMode: atom.inSafeMode()
});
});
});
});
describe('::unloadEditorWindow()', () => {
it('saves the BlobStore so it can be loaded after reload', () => {
const configDirPath = temp.mkdirSync('atom-spec-environment');
const fakeBlobStore = jasmine.createSpyObj('blob store', ['save']);
const atomEnvironment = new AtomEnvironment({
applicationDelegate: atom.applicationDelegate,
enablePersistence: true
});
atomEnvironment.initialize({
configDirPath,
blobStore: fakeBlobStore,
window,
document
});
atomEnvironment.unloadEditorWindow();
expect(fakeBlobStore.save).toHaveBeenCalled();
atomEnvironment.destroy();
});
});
describe('::destroy()', () => {
it('does not throw exceptions when unsubscribing from ipc events (regression)', async () => {
jasmine.useRealClock();
const fakeDocument = {
addEventListener() {},
removeEventListener() {},
head: document.createElement('head'),
body: document.createElement('body')
};
const atomEnvironment = new AtomEnvironment({
applicationDelegate: atom.applicationDelegate
});
atomEnvironment.initialize({ window, document: fakeDocument });
spyOn(atomEnvironment.packages, 'loadPackages').and.returnValue(
Promise.resolve()
);
spyOn(atomEnvironment.packages, 'activate').and.returnValue(Promise.resolve());
spyOn(atomEnvironment, 'displayWindow').and.returnValue(Promise.resolve());
await atomEnvironment.startEditorWindow();
atomEnvironment.unloadEditorWindow();
atomEnvironment.destroy();
});
});
describe('::whenShellEnvironmentLoaded()', () => {
let atomEnvironment, envLoaded, spy;
beforeEach(() => {
let resolvePromise = null;
const promise = new Promise(resolve => {
resolvePromise = resolve;
});
envLoaded = () => {
resolvePromise();
return promise;
};
atomEnvironment = new AtomEnvironment({
applicationDelegate: atom.applicationDelegate,
updateProcessEnv() {
return promise;
}
});
atomEnvironment.initialize({ window, document });
spy = jasmine.createSpy();
});
afterEach(() => atomEnvironment.destroy());
it('is triggered once the shell environment is loaded', async () => {
atomEnvironment.whenShellEnvironmentLoaded(spy);
atomEnvironment.updateProcessEnvAndTriggerHooks();
await envLoaded();
expect(spy).toHaveBeenCalled();
});
it('triggers the callback immediately if the shell environment is already loaded', async () => {
atomEnvironment.updateProcessEnvAndTriggerHooks();
await envLoaded();
atomEnvironment.whenShellEnvironmentLoaded(spy);
expect(spy).toHaveBeenCalled();
});
});
describe('::openLocations(locations)', () => {
beforeEach(() => {
atom.project.setPaths([]);
});
describe('when there is no saved state', () => {
beforeEach(() => {
spyOn(atom, 'loadState').and.returnValue(Promise.resolve(null));
});
describe('when the opened path exists', () => {
it('opens a file', async () => {
const pathToOpen = __filename;
await atom.openLocations([
{ pathToOpen, exists: true, isFile: true }
]);
expect(atom.project.getPaths()).toEqual([]);
});
it('opens a directory as a project folder', async () => {
const pathToOpen = __dirname;
await atom.openLocations([
{ pathToOpen, exists: true, isDirectory: true }
]);
expect(atom.workspace.getTextEditors().map(e => e.getPath())).toEqual(
[]
);
expect(atom.project.getPaths()).toEqual([pathToOpen]);
});
});
describe('when the opened path does not exist', () => {
it('opens it as a new file', async () => {
const pathToOpen = path.join(
__dirname,
'this-path-does-not-exist.txt'
);
await atom.openLocations([{ pathToOpen, exists: false }]);
expect(atom.workspace.getTextEditors().map(e => e.getPath())).toEqual(
[pathToOpen]
);
expect(atom.project.getPaths()).toEqual([]);
});
it('may be required to be an existing directory', async () => {
spyOn(atom.notifications, 'addWarning');
const nonExistent = path.join(__dirname, 'no');
const existingFile = __filename;
const existingDir = path.join(__dirname, 'fixtures');
await atom.openLocations([
{ pathToOpen: nonExistent, isDirectory: true },
{ pathToOpen: existingFile, isDirectory: true },
{ pathToOpen: existingDir, isDirectory: true }
]);
expect(atom.workspace.getTextEditors()).toEqual([]);
expect(atom.project.getPaths()).toEqual([existingDir]);
expect(atom.notifications.addWarning).toHaveBeenCalled();
expect(
atom.notifications.addWarning.calls.mostRecent().args[0],
).toEqual("Unable to open project folders");
expect(
atom.notifications.addWarning.calls.mostRecent().args[1],
).toEqual(
jasmine.objectContaining({
description: `The directories \`${nonExistent}\` and \`${existingFile}\` do not exist.`,
dismissable: true,
buttons: jasmine.arrayContaining([
jasmine.objectContaining({
text: "Remove all",
onDidClick: jasmine.any(Function),
}),
jasmine.objectContaining({
text: "Skip for now",
onDidClick: jasmine.any(Function),
}),
]),
}),
);
});
});
describe('when the opened path is handled by a registered directory provider', () => {
let serviceDisposable;
beforeEach(() => {
serviceDisposable = atom.packages.serviceHub.provide(
'atom.directory-provider',
'0.1.0',
{
directoryForURISync(uri) {
if (uri.startsWith('remote://')) {
return {
getPath() {
return uri;
}
};
} else {
return null;
}
}
}
);
});
afterEach(() => {
serviceDisposable.dispose();
});
it("adds it to the project's paths as is", async () => {
const pathToOpen = 'remote://server:7644/some/dir/path';
spyOn(atom.project, 'addPaths');
await atom.openLocations([{ pathToOpen }]);
expect(atom.project.addPaths).toHaveBeenCalledWith(new Set([pathToOpen]));
});
});
});
describe('when there is saved state for the relevant directories', () => {
const state = Symbol('savedState');
beforeEach(() => {
spyOn(atom, 'getStateKey').and.callFake(dirs => dirs.join(':'));
spyOn(atom, 'loadState').and.callFake(function (key) {
if (key === __dirname) {
return Promise.resolve(state);
} else {
return Promise.resolve(null);
}
});
spyOn(atom, 'attemptRestoreProjectStateForPaths');
});
describe('when there are no project folders', () => {
it('attempts to restore the project state', async () => {
const pathToOpen = __dirname;
await atom.openLocations([{ pathToOpen, isDirectory: true }]);
expect(atom.attemptRestoreProjectStateForPaths).toHaveBeenCalledWith(
state,
[pathToOpen],
[]
);
expect(atom.project.getPaths()).toEqual([]);
});
it('includes missing mandatory project folders in computation of initial state key', async () => {
const existingDir = path.join(__dirname, 'fixtures');
const missingDir = path.join(__dirname, 'no');
atom.loadState.and.callFake(function (key) {
if (key === `${existingDir}:${missingDir}`) {
return Promise.resolve(state);
} else {
return Promise.resolve(null);
}
});
await atom.openLocations([
{ pathToOpen: existingDir },
{ pathToOpen: missingDir, isDirectory: true }
]);
expect(atom.attemptRestoreProjectStateForPaths).toHaveBeenCalledWith(
state,
[existingDir],
[]
);
expect(atom.project.getPaths(), [existingDir]);
});
it('opens the specified files', async () => {
await atom.openLocations([
{ pathToOpen: __dirname, isDirectory: true },
{ pathToOpen: __filename }
]);
expect(atom.attemptRestoreProjectStateForPaths).toHaveBeenCalledWith(
state,
[__dirname],
[__filename]
);
expect(atom.project.getPaths()).toEqual([]);
});
});
describe('when there are already project folders', () => {
beforeEach(() => atom.project.setPaths([__dirname]));
it('does not attempt to restore the project state, instead adding the project paths', async () => {
const pathToOpen = path.join(__dirname, 'fixtures');
await atom.openLocations([
{ pathToOpen, exists: true, isDirectory: true }
]);
expect(
atom.attemptRestoreProjectStateForPaths
).not.toHaveBeenCalled();
expect(atom.project.getPaths()).toEqual([__dirname, pathToOpen]);
});
it('opens the specified files', async () => {
const pathToOpen = path.join(__dirname, 'fixtures');
const fileToOpen = path.join(pathToOpen, 'michelle-is-awesome.txt');
await atom.openLocations([
{ pathToOpen, exists: true, isDirectory: true },
{ pathToOpen: fileToOpen, exists: true, isFile: true }
]);
expect(
atom.attemptRestoreProjectStateForPaths
).not.toHaveBeenCalledWith(state, [pathToOpen], [fileToOpen]);
expect(atom.project.getPaths()).toEqual([__dirname, pathToOpen]);
});
});
});
});
describe('::getReleaseChannel()', () => {
let version;
beforeEach(() => {
spyOn(atom, 'getVersion').and.callFake(() => version);
});
it('returns the correct channel based on the version number', () => {
version = '1.5.6';
expect(atom.getReleaseChannel()).toBe('stable');
version = '1.5.0-beta10';
expect(atom.getReleaseChannel()).toBe('beta');
version = '1.7.0-dev-5340c91';
expect(atom.getReleaseChannel()).toBe('dev');
});
});
describe('::trashItem()', () => {
let fileToBeTrashed, tempDir;
beforeEach(() => {
tempDir = temp.mkdirSync('trash-item-');
fileToBeTrashed = path.join(tempDir, 'file-1.txt');
fs.writeFileSync(fileToBeTrashed, 'test file');
});
it('trashes the file', async () => {
expect(fs.existsSync(fileToBeTrashed)).toBe(true);
await atom.trashItem(fileToBeTrashed);
expect(fs.existsSync(fileToBeTrashed)).toBe(false);
});
it('rejects when asked to trash a nonexistent file', async () => {
let nonexistentFile = path.join(tempDir, 'zzyzx.txt');
expect(fs.existsSync(nonexistentFile)).toBe(false);
let outcome = undefined;
// Assert that the `catch` clause was hit. (`expect().toThrow()` does not
// work with async functions.)
try {
await atom.trashItem(nonexistentFile);
outcome = 'success';
} catch (error) {
outcome = 'failure';
} finally {
expect(outcome).toBe('failure');
}
});
});
});