This repository was archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Expand file tree
/
Copy pathSpecRunnerUtils.js
More file actions
1395 lines (1206 loc) · 54.1 KB
/
SpecRunnerUtils.js
File metadata and controls
1395 lines (1206 loc) · 54.1 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
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global define, $, brackets, jasmine, expect, beforeEach, waitsFor, waitsForDone, runs, spyOn */
define(function (require, exports, module) {
'use strict';
var Commands = require("command/Commands"),
FileUtils = require("file/FileUtils"),
Async = require("utils/Async"),
DocumentManager = require("document/DocumentManager"),
Editor = require("editor/Editor").Editor,
EditorManager = require("editor/EditorManager"),
MainViewManager = require("view/MainViewManager"),
FileSystemError = require("filesystem/FileSystemError"),
FileSystem = require("filesystem/FileSystem"),
WorkspaceManager = require("view/WorkspaceManager"),
ExtensionLoader = require("utils/ExtensionLoader"),
UrlParams = require("utils/UrlParams").UrlParams,
LanguageManager = require("language/LanguageManager");
var TEST_PREFERENCES_KEY = "com.adobe.brackets.test.preferences",
EDITOR_USE_TABS = false,
EDITOR_SPACE_UNITS = 4,
OPEN_TAG = "{{",
RE_MARKER = /\{\{(\d+)\}\}/g,
absPathPrefix = (brackets.platform === "win" ? "c:/" : "/"),
_testSuites = {},
_testWindow,
_doLoadExtensions,
_rootSuite = { id: "__brackets__" },
_unitTestReporter;
MainViewManager._initialize($("#mock-main-view"));
function _getFileSystem() {
return _testWindow ? _testWindow.brackets.test.FileSystem : FileSystem;
}
/**
* Delete a path
* @param {string} fullPath
* @param {boolean=} silent Defaults to false. When true, ignores ERR_NOT_FOUND when deleting path.
* @return {$.Promise} Resolved when deletion complete, or rejected if an error occurs
*/
function deletePath(fullPath, silent) {
var result = new $.Deferred();
_getFileSystem().resolve(fullPath, function (err, item) {
if (!err) {
item.unlink(function (err) {
if (!err) {
result.resolve();
} else {
if (err === FileSystemError.NOT_FOUND && silent) {
result.resolve();
} else {
console.error("Unable to remove " + fullPath, err);
result.reject(err);
}
}
});
} else {
if (err === FileSystemError.NOT_FOUND && silent) {
result.resolve();
} else {
console.error("Unable to remove " + fullPath, err);
result.reject(err);
}
}
});
return result.promise();
}
/**
* Set permissions on a path
* @param {!string} path Path to change permissions on
* @param {!string} mode New mode as an octal string
* @return {$.Promise} Resolved when permissions are set or rejected if an error occurs
*/
function chmod(path, mode) {
var deferred = new $.Deferred();
brackets.fs.chmod(path, parseInt(mode, 8), function (err) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve();
}
});
return deferred.promise();
}
function testDomain() {
return brackets.testing.nodeConnection.domains.testing;
}
/**
* Remove a directory (recursively) or file
*
* @param {!string} path Path to remove
* @return {$.Promise} Resolved when the path is removed, rejected if there was a problem
*/
function remove(path) {
return testDomain().remove(path);
}
/**
* Copy a directory (recursively) or file
*
* @param {!string} src Path to copy
* @param {!string} dest Destination directory
* @return {$.Promise} Resolved when the path is copied, rejected if there was a problem
*/
function copy(src, dest) {
return testDomain().copy(src, dest);
}
/**
* Resolves a path string to a File or Directory
* @param {!string} path Path to a file or directory
* @return {$.Promise} A promise resolved when the file/directory is found or
* rejected when any error occurs.
*/
function resolveNativeFileSystemPath(path) {
var result = new $.Deferred();
_getFileSystem().resolve(path, function (err, item) {
if (!err) {
result.resolve(item);
} else {
result.reject(err);
}
});
return result.promise();
}
/**
* Utility for tests that wait on a Promise to complete. Placed in the global namespace so it can be used
* similarly to the standard Jasmine waitsFor(). Unlike waitsFor(), must be called from INSIDE
* the runs() that generates the promise.
* @param {$.Promise} promise
* @param {string} operationName Name used for timeout error message
*/
window.waitsForDone = function (promise, operationName, timeout) {
timeout = timeout || 1000;
expect(promise).toBeTruthy();
promise.fail(function (err) {
expect("[" + operationName + "] promise rejected with: " + err).toBe("(expected resolved instead)");
});
waitsFor(function () {
return promise.state() === "resolved";
}, "success [" + operationName + "]", timeout);
};
/**
* Utility for tests that waits on a Promise to fail. Placed in the global namespace so it can be used
* similarly to the standards Jasmine waitsFor(). Unlike waitsFor(), must be called from INSIDE
* the runs() that generates the promise.
* @param {$.Promise} promise
* @param {string} operationName Name used for timeout error message
*/
window.waitsForFail = function (promise, operationName, timeout) {
timeout = timeout || 1000;
expect(promise).toBeTruthy();
promise.done(function (result) {
expect("[" + operationName + "] promise resolved with: " + result).toBe("(expected rejected instead)");
});
waitsFor(function () {
return promise.state() === "rejected";
}, "failure " + operationName, timeout);
};
/**
* Utility for *rare* situations in which a test needs to pause for a *known* amount of time.
* Tests that sporadically fail due to timing issues can't really be fixed by this. This function
* was created when a debounce delay was added to updating the project tree, so we have a specific,
* known amount of time to pause for.
*/
window.waitsForTime = function (timeout) {
runs(function () {
var d = new $.Deferred();
setTimeout(function () {
d.resolve();
}, timeout);
waitsForDone(d.promise());
});
};
/**
* Get or create a NativeFileSystem rooted at the system root.
* @return {$.Promise} A promise resolved when the native file system is found or rejected when an error occurs.
*/
function getRoot() {
var deferred = new $.Deferred();
resolveNativeFileSystemPath("/").then(deferred.resolve, deferred.reject);
return deferred.promise();
}
function getTestRoot() {
// /path/to/brackets/test/SpecRunner.html
var path = window.location.pathname;
path = path.substr(0, path.lastIndexOf("/"));
path = FileUtils.convertToNativePath(path);
return path;
}
function getTestPath(path) {
return getTestRoot() + path;
}
/**
* Get the temporary unit test project path. Use this path for unit tests that need to modify files on disk.
* @return {$.string} Path to the temporary unit test project
*/
function getTempDirectory() {
return getTestPath("/temp");
}
/**
* Create the temporary unit test project directory.
*/
function createTempDirectory() {
var deferred = new $.Deferred();
runs(function () {
_getFileSystem().getDirectoryForPath(getTempDirectory()).create(function (err) {
if (err && err !== FileSystemError.ALREADY_EXISTS) {
deferred.reject(err);
} else {
deferred.resolve();
}
});
});
waitsForDone(deferred, "Create temp directory", 500);
}
function _resetPermissionsOnSpecialTempFolders() {
var folders = [],
baseDir = getTempDirectory(),
promise;
folders.push(baseDir + "/cant_read_here");
folders.push(baseDir + "/cant_write_here");
promise = Async.doSequentially(folders, function (folder) {
var deferred = new $.Deferred();
_getFileSystem().resolve(folder, function (err, entry) {
if (!err) {
// Change permissions if the directory exists
chmod(folder, "777").then(deferred.resolve, deferred.reject);
} else {
if (err === FileSystemError.NOT_FOUND) {
// Resolve the promise since the folder to reset doesn't exist
deferred.resolve();
} else {
deferred.reject();
}
}
});
return deferred.promise();
}, true);
return promise;
}
/**
* Remove temp folder used for temporary unit tests files
*/
function removeTempDirectory() {
var deferred = new $.Deferred(),
baseDir = getTempDirectory();
runs(function () {
_resetPermissionsOnSpecialTempFolders().done(function () {
deletePath(baseDir, true).then(deferred.resolve, deferred.reject);
}).fail(function () {
deferred.reject();
});
deferred.fail(function (err) {
console.log("boo");
});
waitsForDone(deferred.promise(), "removeTempDirectory", 1000);
});
}
function getBracketsSourceRoot() {
var path = window.location.pathname;
path = path.split("/");
path = path.slice(0, path.length - 2);
path.push("src");
return path.join("/");
}
/**
* Returns a Document suitable for use with an Editor in isolation, but that can be registered with
* DocumentManager via addRef() so it is maintained for global updates like name and language changes.
*
* Like a normal Document, if you cause an addRef() on this you MUST call releaseRef() later.
*
* @param {!{language:?string, filename:?string, content:?string }} options
* Language defaults to JavaScript, filename defaults to a placeholder name, and
* content defaults to "".
*/
function createMockActiveDocument(options) {
var language = options.language || LanguageManager.getLanguage("javascript"),
filename = options.filename || (absPathPrefix + "_unitTestDummyPath_/_dummyFile_" + Date.now() + "." + language._fileExtensions[0]),
content = options.content || "";
// Use unique filename to avoid collissions in open documents list
var dummyFile = _getFileSystem().getFileForPath(filename);
var docToShim = new DocumentManager.Document(dummyFile, new Date(), content);
// Prevent adding doc to working set by not dispatching "dirtyFlagChange".
// TODO: Other functionality here needs to be kept in sync with Document._handleEditorChange(). In the
// future, we should fix things so that we either don't need mock documents or that this
// is factored so it will just run in both.
docToShim._handleEditorChange = function (event, editor, changeList) {
this.isDirty = !editor._codeMirror.isClean();
this._notifyDocumentChange(changeList);
};
docToShim.notifySaved = function () {
throw new Error("Cannot notifySaved() a unit-test dummy Document");
};
return docToShim;
}
/**
* Returns a Document suitable for use with an Editor in isolation: i.e., a Document that will
* never be set as the currentDocument or added to the working set.
*
* Unlike a real Document, does NOT need to be explicitly cleaned up.
*
* @param {?string} initialContent Defaults to ""
* @param {?string} languageId Defaults to JavaScript
* @param {?string} filename Defaults to an auto-generated filename with the language's extension
*/
function createMockDocument(initialContent, languageId, filename) {
var language = LanguageManager.getLanguage(languageId) || LanguageManager.getLanguage("javascript"),
options = { language: language, content: initialContent, filename: filename },
docToShim = createMockActiveDocument(options);
// Prevent adding doc to global 'open docs' list; prevents leaks or collisions if a test
// fails to clean up properly (if test fails, or due to an apparent bug with afterEach())
docToShim.addRef = function () {};
docToShim.releaseRef = function () {};
docToShim._ensureMasterEditor = function () {
if (!this._masterEditor) {
// Don't let Document create an Editor itself via EditorManager; the unit test can't clean that up
throw new Error("Use create/destroyMockEditor() to test edit operations");
}
};
return docToShim;
}
/**
* Returns a mock element (in the test runner window) that's offscreen, for
* parenting UI you want to unit-test. When done, make sure to delete it with
* remove().
* @return {jQueryObject} a jQuery object for an offscreen div
*/
function createMockElement() {
return $("<div/>")
.css({
position: "absolute",
left: "-10000px",
top: "-10000px"
})
.appendTo($("body"));
}
function createEditorInstance(doc, $editorHolder, visibleRange) {
var editor = new Editor(doc, true, $editorHolder.get(0), visibleRange);
Editor.setUseTabChar(EDITOR_USE_TABS);
Editor.setSpaceUnits(EDITOR_SPACE_UNITS);
EditorManager._notifyActiveEditorChanged(editor);
return editor;
}
/**
* Returns an Editor tied to the given Document, but suitable for use in isolation
* (without being placed inside the surrounding Brackets UI). The Editor *will* be
* reported as the "active editor" by EditorManager.
*
* Must be cleaned up by calling destroyMockEditor(document) later.
*
* @param {!Document} doc
* @param {{startLine: number, endLine: number}=} visibleRange
* @return {!Editor}
*/
function createMockEditorForDocument(doc, visibleRange) {
// Initialize EditorManager/WorkspaceManager and position the editor-holder offscreen
// (".content" may not exist, but that's ok for headless tests where editor height doesn't matter)
var $editorHolder = createMockElement().css("width", "1000px").attr("id", "hidden-editors");
WorkspaceManager._setMockDOM($(".content"), $editorHolder);
// create Editor instance
return createEditorInstance(doc, $editorHolder, visibleRange);
}
/**
* Returns a Document and Editor suitable for use in isolation: the Document
* will never be set as the currentDocument or added to the working set and the
* Editor does not live inside a full-blown Brackets UI layout. The Editor *will* be
* reported as the "active editor" by EditorManager, however.
*
* Must be cleaned up by calling destroyMockEditor(document) later.
*
* @param {string=} initialContent
* @param {string=} languageId
* @param {{startLine: number, endLine: number}=} visibleRange
* @return {!{doc:!Document, editor:!Editor}}
*/
function createMockEditor(initialContent, languageId, visibleRange) {
// create dummy Document, then Editor tied to it
var doc = createMockDocument(initialContent, languageId);
return { doc: doc, editor: createMockEditorForDocument(doc, visibleRange) };
}
function createMockPane($el) {
createMockElement()
.attr("class", "pane-header")
.appendTo($el);
var $fakeContent = createMockElement()
.attr("class", "pane-content")
.appendTo($el);
return {
$el: $el,
$content: $fakeContent,
addView: function (path, editor) {
},
showView: function (editor) {
}
};
}
/**
* Destroy the Editor instance for a given mock Document.
* @param {!Document} doc Document whose master editor to destroy
*/
function destroyMockEditor(doc) {
EditorManager._notifyActiveEditorChanged(null);
MainViewManager._destroyEditorIfNotNeeded(doc);
// Clear editor holder so EditorManager doesn't try to resize destroyed object
$("#hidden-editors").remove();
}
/**
* Dismiss the currently open dialog as if the user had chosen the given button. Dialogs close
* asynchronously; after calling this, you need to start a new runs() block before testing the
* outcome. Also, in cases where asynchronous tasks are performed after the dialog closes,
* clients must also wait for any additional promises.
* @param {string} buttonId One of the Dialogs.DIALOG_BTN_* symbolic constants.
* @param {boolean=} enableFirst If true, then enable the button before clicking.
*/
function clickDialogButton(buttonId, enableFirst) {
// Make sure there's one and only one dialog open
var $dlg = _testWindow.$(".modal.instance"),
promise = $dlg.data("promise");
expect($dlg.length).toBe(1);
// Make sure desired button exists
var $dismissButton = $dlg.find(".dialog-button[data-button-id='" + buttonId + "']");
expect($dismissButton.length).toBe(1);
if (enableFirst) {
// Remove the disabled prop.
$dismissButton.prop("disabled", false);
}
// Click the button
$dismissButton.click();
// Dialog should resolve/reject the promise
waitsForDone(promise, "dismiss dialog");
}
function createTestWindowAndRun(spec, callback, options) {
runs(function () {
// Position popup windows in the lower right so they're out of the way
var testWindowWid = 1000,
testWindowHt = 700,
testWindowX = window.screen.availWidth - testWindowWid,
testWindowY = window.screen.availHeight - testWindowHt,
optionsStr = "left=" + testWindowX + ",top=" + testWindowY +
",width=" + testWindowWid + ",height=" + testWindowHt;
var params = new UrlParams();
// setup extension loading in the test window
params.put("extensions", _doLoadExtensions ?
"default,dev," + ExtensionLoader.getUserExtensionPath() :
"default");
// disable update check in test windows
params.put("skipUpdateCheck", true);
// disable loading of sample project
params.put("skipSampleProjectLoad", true);
// disable initial dialog for live development
params.put("skipLiveDevelopmentInfo", true);
// signals that main.js should configure RequireJS for tests
params.put("testEnvironment", true);
// option to launch test window with either native or HTML menus
if (options && options.hasOwnProperty("hasNativeMenus")) {
params.put("hasNativeMenus", (options.hasNativeMenus ? "true" : "false"));
}
_testWindow = window.open(getBracketsSourceRoot() + "/index.html?" + params.toString(), "_blank", optionsStr);
// Displays the primary console messages from the test window in the the
// test runner's console as well.
["debug", "log", "info", "warn", "error"].forEach(function (method) {
var originalMethod = _testWindow.console[method];
_testWindow.console[method] = function () {
var log = ["[testWindow] "].concat(Array.prototype.slice.call(arguments, 0));
console[method].apply(console, log);
originalMethod.apply(_testWindow.console, arguments);
};
});
_testWindow.isBracketsTestWindow = true;
_testWindow.executeCommand = function executeCommand(cmd, args) {
return _testWindow.brackets.test.CommandManager.execute(cmd, args);
};
_testWindow.closeAllFiles = function closeAllFiles() {
runs(function () {
var promise = _testWindow.executeCommand(_testWindow.brackets.test.Commands.FILE_CLOSE_ALL);
_testWindow.brackets.test.Dialogs.cancelModalDialogIfOpen(
_testWindow.brackets.test.DefaultDialogs.DIALOG_ID_SAVE_CLOSE,
_testWindow.brackets.test.DefaultDialogs.DIALOG_BTN_DONTSAVE
);
waitsForDone(promise, "Close all open files in working set");
});
};
});
// FIXME (issue #249): Need an event or something a little more reliable...
waitsFor(
function isBracketsDoneLoading() {
return _testWindow.brackets && _testWindow.brackets.test && _testWindow.brackets.test.doneLoading;
},
"brackets.test.doneLoading",
10000
);
runs(function () {
// callback allows specs to query the testWindow before they run
callback.call(spec, _testWindow);
});
}
function closeTestWindow() {
// debug-only to see testWindow state before closing
// waits(500);
runs(function () {
//we need to mark the documents as not dirty before we close
//or the window will stay open prompting to save
var openDocs = _testWindow.brackets.test.DocumentManager.getAllOpenDocuments();
openDocs.forEach(function resetDoc(doc) {
if (doc.isDirty) {
//just refresh it back to it's current text. This will mark it
//clean to save
doc.refreshText(doc.getText(), doc.diskTimestamp);
}
});
_testWindow.close();
_testWindow.executeCommand = null;
_testWindow = null;
});
}
function loadProjectInTestWindow(path) {
runs(function () {
// begin loading project path
var result = _testWindow.brackets.test.ProjectManager.openProject(path);
// wait for file system to finish loading
waitsForDone(result, "ProjectManager.openProject()", 10000);
});
}
/**
* Parses offsets from text offset markup (e.g. "{{1}}" for offset 1).
* @param {!string} text Text to parse
* @return {!{offsets:!Array.<{line:number, ch:number}>, text:!string, original:!string}}
*/
function parseOffsetsFromText(text) {
var offsets = [],
output = [],
i = 0,
line = 0,
charAt = 0,
ch = 0,
length = text.length,
exec = null,
found = false;
while (i < length) {
found = false;
if (text.slice(i, i + OPEN_TAG.length) === OPEN_TAG) {
// find "{{[0-9]+}}"
RE_MARKER.lastIndex = i;
exec = RE_MARKER.exec(text);
found = (exec !== null && exec.index === i);
if (found) {
// record offset info
offsets[exec[1]] = {line: line, ch: ch};
// advance
i += exec[0].length;
}
}
if (!found) {
charAt = text.substr(i, 1);
output.push(charAt);
if (charAt === '\n') {
line++;
ch = 0;
} else {
ch++;
}
i++;
}
}
return {offsets: offsets, text: output.join(""), original: text};
}
/**
* Creates absolute paths based on the test window's current project
* @param {!Array.<string>|string} paths Project relative file path(s) to convert. May pass a single string path or array.
* @return {!Array.<string>|string} Absolute file path(s)
*/
function makeAbsolute(paths) {
var fullPath = _testWindow.brackets.test.ProjectManager.getProjectRoot().fullPath;
function prefixProjectPath(path) {
if (path.indexOf(fullPath) === 0) {
return path;
}
return fullPath + path;
}
if (Array.isArray(paths)) {
return paths.map(prefixProjectPath);
} else {
return prefixProjectPath(paths);
}
}
/**
* Creates relative paths based on the test window's current project. Any paths,
* outside the project are included in the result, but left as absolute paths.
* @param {!Array.<string>|string} paths Absolute file path(s) to convert. May pass a single string path or array.
* @return {!Array.<string>|string} Relative file path(s)
*/
function makeRelative(paths) {
var fullPath = _testWindow.brackets.test.ProjectManager.getProjectRoot().fullPath,
fullPathLength = fullPath.length;
function removeProjectPath(path) {
if (path.indexOf(fullPath) === 0) {
return path.substring(fullPathLength);
}
return path;
}
if (Array.isArray(paths)) {
return paths.map(removeProjectPath);
} else {
return removeProjectPath(paths);
}
}
function makeArray(arg) {
if (!Array.isArray(arg)) {
return [arg];
}
return arg;
}
/**
* Opens project relative file paths in the test window
* @param {!(Array.<string>|string)} paths Project relative file path(s) to open
* @return {!$.Promise} A promise resolved with a mapping of project-relative path
* keys to a corresponding Document
*/
function openProjectFiles(paths) {
var result = new $.Deferred(),
fullpaths = makeArray(makeAbsolute(paths)),
keys = makeArray(makeRelative(paths)),
docs = {},
FileViewController = _testWindow.brackets.test.FileViewController,
DocumentManager = _testWindow.brackets.test.DocumentManager;
Async.doSequentially(fullpaths, function (path, i) {
var one = new $.Deferred();
FileViewController.openFileAndAddToWorkingSet(path).done(function (file) {
docs[keys[i]] = DocumentManager.getOpenDocumentForPath(file.fullPath);
one.resolve();
}).fail(function (err) {
one.reject(err);
});
return one.promise();
}, false).done(function () {
result.resolve(docs);
}).fail(function (err) {
result.reject(err);
}).always(function () {
docs = null;
FileViewController = null;
});
return result.promise();
}
/**
* Create or overwrite a text file
* @param {!string} path Path for a file to be created/overwritten
* @param {!string} text Text content for the new file
* @param {!FileSystem} fileSystem FileSystem instance to use. Normally, use the instance from
* testWindow so the test copy of Brackets is aware of the newly-created file.
* @return {$.Promise} A promise resolved when the file is written or rejected when an error occurs.
*/
function createTextFile(path, text, fileSystem) {
var deferred = new $.Deferred(),
file = fileSystem.getFileForPath(path),
options = {
blind: true // overwriting previous files is OK
};
file.write(text, options, function (err) {
if (!err) {
deferred.resolve(file);
} else {
deferred.reject(err);
}
});
return deferred.promise();
}
/**
* Copy a file source path to a destination
* @param {!File} source Entry for the source file to copy
* @param {!string} destination Destination path to copy the source file
* @param {?{parseOffsets:boolean}} options parseOffsets allows optional
* offset markup parsing. File is written to the destination path
* without offsets. Offset data is passed to the doneCallbacks of the
* promise.
* @return {$.Promise} A promise resolved when the file is copied to the
* destination.
*/
function copyFileEntry(source, destination, options) {
options = options || {};
var deferred = new $.Deferred();
// read the source file
FileUtils.readAsText(source).done(function (text, modificationTime) {
getRoot().done(function (nfs) {
var offsets;
// optionally parse offsets
if (options.parseOffsets) {
var parseInfo = parseOffsetsFromText(text);
text = parseInfo.text;
offsets = parseInfo.offsets;
}
// create the new File
createTextFile(destination, text, _getFileSystem()).done(function (entry) {
deferred.resolve(entry, offsets, text);
}).fail(function (err) {
deferred.reject(err);
});
});
}).fail(function (err) {
deferred.reject(err);
});
return deferred.promise();
}
/**
* Copy a directory source to a destination
* @param {!Directory} source Directory to copy
* @param {!string} destination Destination path to copy the source directory to
* @param {?{parseOffsets:boolean, infos:Object, removePrefix:boolean}}} options
* parseOffsets - allows optional offset markup parsing. File is written to the
* destination path without offsets. Offset data is passed to the
* doneCallbacks of the promise.
* infos - an optional Object used when parseOffsets is true. Offset
* information is attached here, indexed by the file destination path.
* removePrefix - When parseOffsets is true, set removePrefix true
* to add a new key to the infos array that drops the destination
* path root.
* @return {$.Promise} A promise resolved when the directory and all it's
* contents are copied to the destination or rejected immediately
* upon the first error.
*/
function copyDirectoryEntry(source, destination, options) {
options = options || {};
options.infos = options.infos || {};
var parseOffsets = options.parseOffsets || false,
removePrefix = options.removePrefix || true,
deferred = new $.Deferred(),
destDir = _getFileSystem().getDirectoryForPath(destination);
// create the destination folder
destDir.create(function (err) {
if (err && err !== FileSystemError.ALREADY_EXISTS) {
deferred.reject();
return;
}
source.getContents(function (err, contents) {
if (!err) {
// copy all children of this directory
var copyChildrenPromise = Async.doInParallel(
contents,
function copyChild(child) {
var childDestination = destination + "/" + child.name,
promise;
if (child.isDirectory) {
promise = copyDirectoryEntry(child, childDestination, options);
} else {
promise = copyFileEntry(child, childDestination, options);
if (parseOffsets) {
// save offset data for each file path
promise.done(function (destinationEntry, offsets, text) {
options.infos[childDestination] = {
offsets : offsets,
fileEntry : destinationEntry,
text : text
};
});
}
}
return promise;
}
);
copyChildrenPromise.then(deferred.resolve, deferred.reject);
} else {
deferred.reject(err);
}
});
});
deferred.always(function () {
// remove destination path prefix
if (removePrefix && options.infos) {
var shortKey;
Object.keys(options.infos).forEach(function (key) {
shortKey = key.substr(destination.length + 1);
options.infos[shortKey] = options.infos[key];
});
}
});
return deferred.promise();
}
/**
* Copy a file or directory source path to a destination
* @param {!string} source Path for the source file or directory to copy
* @param {!string} destination Destination path to copy the source file or directory
* @param {?{parseOffsets:boolean, infos:Object, removePrefix:boolean}}} options
* parseOffsets - allows optional offset markup parsing. File is written to the
* destination path without offsets. Offset data is passed to the
* doneCallbacks of the promise.
* infos - an optional Object used when parseOffsets is true. Offset
* information is attached here, indexed by the file destination path.
* removePrefix - When parseOffsets is true, set removePrefix true
* to add a new key to the infos array that drops the destination
* path root.
* @return {$.Promise} A promise resolved when the directory and all it's
* contents are copied to the destination or rejected immediately
* upon the first error.
*/
function copyPath(source, destination, options) {
var deferred = new $.Deferred();
resolveNativeFileSystemPath(source).done(function (entry) {
var promise;
if (entry.isDirectory) {
promise = copyDirectoryEntry(entry, destination, options);
} else {
promise = copyFileEntry(entry, destination, options);
}
promise.then(deferred.resolve, function (err) {
console.error(destination);
deferred.reject();
});
}).fail(function () {
deferred.reject();
});
return deferred.promise();
}
/**
* Set editor cursor position to the given offset then activate an inline editor.
* @param {!Editor} editor
* @param {!{line:number, ch:number}} offset
* @return {$.Promise} a promise that will be resolved when an inline
* editor is created or rejected when no inline editors are available.
*/
function toggleQuickEditAtOffset(editor, offset) {
editor.setCursorPos(offset.line, offset.ch);
return _testWindow.executeCommand(Commands.TOGGLE_QUICK_EDIT);
}
/**
* Simulate key event. Found this code here:
* http://stackoverflow.com/questions/10455626/keydown-simulation-in-chrome-fires-normally-but-not-the-correct-key
*
* TODO: need parameter(s) for modifier keys
*
* @param {Number} key Key code
* @param (String) event Key event to simulate
* @param {HTMLElement} element Element to receive event
*/
function simulateKeyEvent(key, event, element) {
var doc = element.ownerDocument,
oEvent = doc.createEvent('KeyboardEvent');
if (event !== "keydown" && event !== "keyup" && event !== "keypress") {
console.log("SpecRunnerUtils.simulateKeyEvent() - unsupported keyevent: " + event);
return;
}
// Chromium Hack: need to override the 'which' property.