forked from adobe/brackets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindInFiles-test.js
More file actions
2195 lines (1886 loc) · 112 KB
/
FindInFiles-test.js
File metadata and controls
2195 lines (1886 loc) · 112 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) 2014 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, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global define, describe, it, expect, beforeFirst, afterLast, beforeEach, afterEach, waits, waitsFor, waitsForDone, runs, window, jasmine, spyOn */
define(function (require, exports, module) {
"use strict";
var Commands = require("command/Commands"),
KeyEvent = require("utils/KeyEvent"),
SpecRunnerUtils = require("spec/SpecRunnerUtils"),
FileSystem = require("filesystem/FileSystem"),
FileSystemError = require("filesystem/FileSystemError"),
FileUtils = require("file/FileUtils"),
FindUtils = require("search/FindUtils"),
Async = require("utils/Async"),
LanguageManager = require("language/LanguageManager"),
StringUtils = require("utils/StringUtils"),
Strings = require("strings"),
_ = require("thirdparty/lodash");
var promisify = Async.promisify; // for convenience
describe("FindInFiles", function () {
this.category = "integration";
var defaultSourcePath = SpecRunnerUtils.getTestPath("/spec/FindReplace-test-files"),
testPath,
nextFolderIndex = 1,
searchResults,
CommandManager,
DocumentManager,
EditorManager,
FileFilters,
FileSystem,
File,
FindInFiles,
FindInFilesUI,
ProjectManager,
testWindow,
$;
beforeFirst(function () {
SpecRunnerUtils.createTempDirectory();
// Create a new window that will be shared by ALL tests in this spec.
SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
testWindow = w;
// Load module instances from brackets.test
CommandManager = testWindow.brackets.test.CommandManager;
DocumentManager = testWindow.brackets.test.DocumentManager;
EditorManager = testWindow.brackets.test.EditorManager;
FileFilters = testWindow.brackets.test.FileFilters;
FileSystem = testWindow.brackets.test.FileSystem;
File = testWindow.brackets.test.File;
FindInFiles = testWindow.brackets.test.FindInFiles;
FindInFilesUI = testWindow.brackets.test.FindInFilesUI;
ProjectManager = testWindow.brackets.test.ProjectManager;
$ = testWindow.$;
});
});
afterLast(function () {
CommandManager = null;
DocumentManager = null;
EditorManager = null;
FileSystem = null;
File = null;
FindInFiles = null;
FindInFilesUI = null;
ProjectManager = null;
$ = null;
testWindow = null;
SpecRunnerUtils.closeTestWindow();
SpecRunnerUtils.removeTempDirectory();
});
function openProject(sourcePath) {
testPath = sourcePath;
SpecRunnerUtils.loadProjectInTestWindow(testPath);
}
function waitForSearchBarClose() {
// Make sure search bar from previous test has animated out fully
waitsFor(function () {
return $(".modal-bar").length === 0;
}, "search bar close");
}
function openSearchBar(scope, showReplace) {
waitForSearchBarClose();
runs(function () {
FindInFiles._searchDone = false;
FindInFilesUI._showFindBar(scope, showReplace);
});
waitsFor(function () {
return $(".modal-bar").length === 1;
}, "search bar open");
runs(function () {
// Reset the regexp and case-sensitivity toggles.
["#find-regexp", "#find-case-sensitive"].forEach(function (button) {
if ($(button).is(".active")) {
$(button).click();
expect($(button).is(".active")).toBe(false);
}
});
});
}
function closeSearchBar() {
runs(function () {
FindInFilesUI._closeFindBar();
});
waitForSearchBarClose();
}
function executeSearch(searchString) {
runs(function () {
var $searchField = $("#find-what");
$searchField.val(searchString).trigger("input");
SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_RETURN, "keydown", $searchField[0]);
});
waitsFor(function () {
return FindInFiles._searchDone;
}, "Find in Files done");
}
function numMatches(results) {
return _.reduce(_.pluck(results, "matches"), function (sum, matches) {
return sum + matches.length;
}, 0);
}
function doSearch(options) {
runs(function () {
FindInFiles.doSearchInScope(options.queryInfo, null, null, options.replaceText).done(function (results) {
searchResults = results;
});
});
waitsFor(function () { return searchResults; }, 1000, "search completed");
runs(function () {
expect(numMatches(searchResults)).toBe(options.numMatches);
});
}
function doReplace(options) {
return FindInFiles.doReplace(searchResults, options.replaceText, {
forceFilesOpen: options.forceFilesOpen,
isRegexp: options.queryInfo.isRegexp
});
}
/**
* Helper function that calls the given asynchronous processor once on each file in the given subtree
* and returns a promise that's resolved when all files are processed.
* @param {string} rootPath The root of the subtree to search.
* @param {function(string, string): $.Promise} processor The function that processes each file. Args are:
* contents: the contents of the file
* fullPath: the full path to the file on disk
* @return {$.Promise} A promise that is resolved when all files are processed, or rejected if there was
* an error reading one of the files or one of the process steps was rejected.
*/
function visitAndProcessFiles(rootPath, processor) {
var rootEntry = FileSystem.getDirectoryForPath(rootPath),
files = [];
function visitor(file) {
if (!file.isDirectory) {
// Skip binary files, since we don't care about them for these purposes and we can't read them
// to get their contents.
if (!LanguageManager.getLanguageForPath(file.fullPath).isBinary()) {
files.push(file);
}
}
return true;
}
return promisify(rootEntry, "visit", visitor).then(function () {
return Async.doInParallel(files, function (file) {
return promisify(file, "read").then(function (contents) {
return processor(contents, file.fullPath);
});
});
});
}
function ensureParentExists(file) {
var parentDir = FileSystem.getDirectoryForPath(file.parentPath);
return promisify(parentDir, "exists").then(function (exists) {
if (!exists) {
return promisify(parentDir, "create");
}
return null;
});
}
function copyWithLineEndings(src, dest, lineEndings) {
function copyOneFileWithLineEndings(contents, srcPath) {
var destPath = dest + srcPath.slice(src.length),
destFile = FileSystem.getFileForPath(destPath),
newContents = FileUtils.translateLineEndings(contents, lineEndings);
return ensureParentExists(destFile).then(function () {
return promisify(destFile, "write", newContents);
});
}
return promisify(FileSystem.getDirectoryForPath(dest), "create").then(function () {
return visitAndProcessFiles(src, copyOneFileWithLineEndings);
});
}
// Creates a clean copy of the test project before each test. We don't delete the old
// folders as we go along (to avoid problems with deleting the project out from under the
// open test window); we just delete the whole temp folder at the end.
function openTestProjectCopy(sourcePath, lineEndings) {
testPath = SpecRunnerUtils.getTempDirectory() + "/find-in-files-test-" + (nextFolderIndex++);
runs(function () {
if (lineEndings) {
waitsForDone(copyWithLineEndings(sourcePath, testPath, lineEndings), "copy test files with line endings");
} else {
// Note that we don't skip image files in this case, but it doesn't matter since we'll
// only compare files that have an associated file in the known goods folder.
waitsForDone(SpecRunnerUtils.copy(sourcePath, testPath), "copy test files");
}
});
SpecRunnerUtils.loadProjectInTestWindow(testPath);
}
beforeEach(function () {
searchResults = null;
});
describe("Find", function () {
beforeEach(function () {
openProject(defaultSourcePath);
});
it("should find all occurences in project", function () {
openSearchBar();
executeSearch("foo");
runs(function () {
var fileResults = FindInFiles.searchModel.results[testPath + "/bar.txt"];
expect(fileResults).toBeFalsy();
fileResults = FindInFiles.searchModel.results[testPath + "/foo.html"];
expect(fileResults).toBeTruthy();
expect(fileResults.matches.length).toBe(7);
fileResults = FindInFiles.searchModel.results[testPath + "/foo.js"];
expect(fileResults).toBeTruthy();
expect(fileResults.matches.length).toBe(4);
fileResults = FindInFiles.searchModel.results[testPath + "/css/foo.css"];
expect(fileResults).toBeTruthy();
expect(fileResults.matches.length).toBe(3);
});
});
it("should ignore binary files", function () {
var $dlg, actualMessage, expectedMessage,
exists = false,
done = false,
imageDirPath = testPath + "/images";
runs(function () {
// Set project to have only images
SpecRunnerUtils.loadProjectInTestWindow(imageDirPath);
// Verify an image exists in folder
var file = FileSystem.getFileForPath(testPath + "/images/icon_twitter.png");
file.exists(function (fileError, fileExists) {
exists = fileExists;
done = true;
});
});
waitsFor(function () {
return done;
}, "file.exists");
runs(function () {
expect(exists).toBe(true);
openSearchBar();
});
runs(function () {
// Launch filter editor
FileFilters.editFilter({ name: "", patterns: [] }, -1);
// Dialog should state there are 0 files in project
$dlg = $(".modal");
expectedMessage = StringUtils.format(Strings.FILTER_FILE_COUNT_ALL, 0, Strings.FIND_IN_FILES_NO_SCOPE);
});
// Message loads asynchronously, but dialog should eventually state: "Allows all 0 files in project"
waitsFor(function () {
actualMessage = $dlg.find(".exclusions-filecount").text();
return (actualMessage === expectedMessage);
}, "display file count");
runs(function () {
// Dismiss filter dialog (OK button is disabled, have to click on Cancel)
$dlg.find(".dialog-button[data-button-id='cancel']").click();
// Close search bar
var $searchField = $(".modal-bar #find-group input");
SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_ESCAPE, "keydown", $searchField[0]);
});
runs(function () {
// Set project back to main test folder
SpecRunnerUtils.loadProjectInTestWindow(testPath);
});
});
it("should find all occurences in folder", function () {
var dirEntry = FileSystem.getDirectoryForPath(testPath + "/css/");
openSearchBar(dirEntry);
executeSearch("foo");
runs(function () {
var fileResults = FindInFiles.searchModel.results[testPath + "/bar.txt"];
expect(fileResults).toBeFalsy();
fileResults = FindInFiles.searchModel.results[testPath + "/foo.html"];
expect(fileResults).toBeFalsy();
fileResults = FindInFiles.searchModel.results[testPath + "/foo.js"];
expect(fileResults).toBeFalsy();
fileResults = FindInFiles.searchModel.results[testPath + "/css/foo.css"];
expect(fileResults).toBeTruthy();
expect(fileResults.matches.length).toBe(3);
});
});
it("should find all occurences in single file", function () {
var fileEntry = FileSystem.getFileForPath(testPath + "/foo.js");
openSearchBar(fileEntry);
executeSearch("foo");
runs(function () {
var fileResults = FindInFiles.searchModel.results[testPath + "/bar.txt"];
expect(fileResults).toBeFalsy();
fileResults = FindInFiles.searchModel.results[testPath + "/foo.html"];
expect(fileResults).toBeFalsy();
fileResults = FindInFiles.searchModel.results[testPath + "/foo.js"];
expect(fileResults).toBeTruthy();
expect(fileResults.matches.length).toBe(4);
fileResults = FindInFiles.searchModel.results[testPath + "/css/foo.css"];
expect(fileResults).toBeFalsy();
});
});
it("should find start and end positions", function () {
var filePath = testPath + "/foo.js",
fileEntry = FileSystem.getFileForPath(filePath);
openSearchBar(fileEntry);
executeSearch("callFoo");
runs(function () {
var fileResults = FindInFiles.searchModel.results[filePath];
expect(fileResults).toBeTruthy();
expect(fileResults.matches.length).toBe(1);
var match = fileResults.matches[0];
expect(match.start.ch).toBe(13);
expect(match.start.line).toBe(6);
expect(match.end.ch).toBe(20);
expect(match.end.line).toBe(6);
});
});
it("should dismiss dialog and show panel when there are results", function () {
var filePath = testPath + "/foo.js",
fileEntry = FileSystem.getFileForPath(filePath);
openSearchBar(fileEntry);
executeSearch("callFoo");
waitsFor(function () {
return ($(".modal-bar").length === 0);
}, "search bar close");
runs(function () {
var fileResults = FindInFiles.searchModel.results[filePath];
expect(fileResults).toBeTruthy();
expect($("#find-in-files-results").is(":visible")).toBeTruthy();
expect($(".modal-bar").length).toBe(0);
});
});
it("should keep dialog and not show panel when there are no results", function () {
var filePath = testPath + "/bar.txt",
fileEntry = FileSystem.getFileForPath(filePath);
openSearchBar(fileEntry);
executeSearch("abcdefghi");
waitsFor(function () {
return (FindInFiles._searchDone);
}, "search complete");
runs(function () {
var result, resultFound = false;
// verify searchModel.results Object is empty
for (result in FindInFiles.searchModel.results) {
if (FindInFiles.searchModel.results.hasOwnProperty(result)) {
resultFound = true;
}
}
expect(resultFound).toBe(false);
expect($("#find-in-files-results").is(":visible")).toBeFalsy();
expect($(".modal-bar").length).toBe(1);
// Close search bar
var $searchField = $(".modal-bar #find-group input");
SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_ESCAPE, "keydown", $searchField[0]);
});
});
it("should open file in editor and select text when a result is clicked", function () {
var filePath = testPath + "/foo.html",
fileEntry = FileSystem.getFileForPath(filePath);
openSearchBar(fileEntry);
executeSearch("foo");
runs(function () {
// Verify no current document
var editor = EditorManager.getActiveEditor();
expect(editor).toBeFalsy();
// Get panel
var $searchResults = $("#find-in-files-results");
expect($searchResults.is(":visible")).toBeTruthy();
// Get list in panel
var $panelResults = $searchResults.find("table.bottom-panel-table tr");
expect($panelResults.length).toBe(8); // 7 hits + 1 file section
// First item in list is file section
expect($($panelResults[0]).hasClass("file-section")).toBeTruthy();
// Click second item which is first hit
var $firstHit = $($panelResults[1]);
expect($firstHit.hasClass("file-section")).toBeFalsy();
$firstHit.click();
// Verify current document
editor = EditorManager.getActiveEditor();
expect(editor.document.file.fullPath).toEqual(filePath);
// Verify selection
expect(editor.getSelectedText().toLowerCase() === "foo");
waitsForDone(CommandManager.execute(Commands.FILE_CLOSE_ALL), "closing all files");
});
});
it("should open file in working set when a result is double-clicked", function () {
var filePath = testPath + "/foo.js",
fileEntry = FileSystem.getFileForPath(filePath);
openSearchBar(fileEntry);
executeSearch("foo");
runs(function () {
// Verify document is not yet in working set
expect(DocumentManager.findInWorkingSet(filePath)).toBe(-1);
// Get list in panel
var $panelResults = $("#find-in-files-results table.bottom-panel-table tr");
expect($panelResults.length).toBe(5); // 4 hits + 1 file section
// Double-click second item which is first hit
var $firstHit = $($panelResults[1]);
expect($firstHit.hasClass("file-section")).toBeFalsy();
$firstHit.dblclick();
// Verify document is now in working set
expect(DocumentManager.findInWorkingSet(filePath)).not.toBe(-1);
waitsForDone(CommandManager.execute(Commands.FILE_CLOSE_ALL), "closing all files");
});
});
it("should update results when a result in a file is edited", function () {
var filePath = testPath + "/foo.html",
fileEntry = FileSystem.getFileForPath(filePath),
panelListLen = 8, // 7 hits + 1 file section
$panelResults;
openSearchBar(fileEntry);
executeSearch("foo");
runs(function () {
// Verify document is not yet in working set
expect(DocumentManager.findInWorkingSet(filePath)).toBe(-1);
// Get list in panel
$panelResults = $("#find-in-files-results table.bottom-panel-table tr");
expect($panelResults.length).toBe(panelListLen);
// Click second item which is first hit
var $firstHit = $($panelResults[1]);
expect($firstHit.hasClass("file-section")).toBeFalsy();
$firstHit.click();
});
// Wait for file to open if not already open
waitsFor(function () {
var editor = EditorManager.getActiveEditor();
return (editor.document.file.fullPath === filePath);
}, 1000, "file open");
// Wait for selection to change (this happens asynchronously after file opens)
waitsFor(function () {
var editor = EditorManager.getActiveEditor(),
sel = editor.getSelection();
return (sel.start.line === 4 && sel.start.ch === 7);
}, 1000, "selection change");
runs(function () {
// Verify current selection
var editor = EditorManager.getActiveEditor();
expect(editor.getSelectedText().toLowerCase()).toBe("foo");
// Edit text to remove hit from file
var sel = editor.getSelection();
editor.document.replaceRange("Bar", sel.start, sel.end);
});
// Panel is updated asynchronously
waitsFor(function () {
$panelResults = $("#find-in-files-results table.bottom-panel-table tr");
return ($panelResults.length < panelListLen);
}, "Results panel updated");
runs(function () {
// Verify list automatically updated
expect($panelResults.length).toBe(panelListLen - 1);
waitsForDone(CommandManager.execute(Commands.FILE_CLOSE, { _forceClose: true }), "closing file");
});
});
});
describe("Find results paging", function () {
var expectedPages = [
{
totalResults: 500,
totalFiles: 2,
overallFirstIndex: 1,
overallLastIndex: 100,
matchRanges: [{file: 0, filename: "manyhits-1.txt", first: 0, firstLine: 1, last: 99, lastLine: 100, pattern: /i'm going to\s+find this\s+now/}],
firstPageEnabled: false,
lastPageEnabled: true,
prevPageEnabled: false,
nextPageEnabled: true
},
{
totalResults: 500,
totalFiles: 2,
overallFirstIndex: 101,
overallLastIndex: 200,
matchRanges: [{file: 0, filename: "manyhits-1.txt", first: 0, firstLine: 101, last: 99, lastLine: 200, pattern: /i'm going to\s+find this\s+now/}],
firstPageEnabled: true,
lastPageEnabled: true,
prevPageEnabled: true,
nextPageEnabled: true
},
{
totalResults: 500,
totalFiles: 2,
overallFirstIndex: 201,
overallLastIndex: 300,
matchRanges: [
{file: 0, filename: "manyhits-1.txt", first: 0, firstLine: 201, last: 49, lastLine: 250, pattern: /i'm going to\s+find this\s+now/},
{file: 1, filename: "manyhits-2.txt", first: 0, firstLine: 1, last: 49, lastLine: 50, pattern: /you're going to\s+find this\s+now/}
],
firstPageEnabled: true,
lastPageEnabled: true,
prevPageEnabled: true,
nextPageEnabled: true
},
{
totalResults: 500,
totalFiles: 2,
overallFirstIndex: 301,
overallLastIndex: 400,
matchRanges: [{file: 0, filename: "manyhits-2.txt", first: 0, firstLine: 51, last: 99, lastLine: 150, pattern: /you're going to\s+find this\s+now/}],
firstPageEnabled: true,
lastPageEnabled: true,
prevPageEnabled: true,
nextPageEnabled: true
},
{
totalResults: 500,
totalFiles: 2,
overallFirstIndex: 401,
overallLastIndex: 500,
matchRanges: [{file: 0, filename: "manyhits-2.txt", first: 0, firstLine: 151, last: 99, lastLine: 250, pattern: /you're going to\s+find this\s+now/}],
firstPageEnabled: true,
lastPageEnabled: false,
prevPageEnabled: true,
nextPageEnabled: false
}
];
function expectPageDisplay(options) {
// Check the title
expect($("#find-in-files-results .title").text().match("\\b" + options.totalResults + "\\b")).toBeTruthy();
expect($("#find-in-files-results .title").text().match("\\b" + options.totalFiles + "\\b")).toBeTruthy();
var paginationInfo = $("#find-in-files-results .pagination-col").text();
expect(paginationInfo.match("\\b" + options.overallFirstIndex + "\\b")).toBeTruthy();
expect(paginationInfo.match("\\b" + options.overallLastIndex + "\\b")).toBeTruthy();
// Check for presence of file and first/last item rows within each file
options.matchRanges.forEach(function (range) {
var $fileRow = $("#find-in-files-results tr.file-section[data-file-index='" + range.file + "']");
expect($fileRow.length).toBe(1);
expect($fileRow.find(".dialog-filename").text()).toEqual(range.filename);
var $firstMatchRow = $("#find-in-files-results tr[data-file-index='" + range.file + "'][data-item-index='" + range.first + "']");
expect($firstMatchRow.length).toBe(1);
expect($firstMatchRow.find(".line-number").text().match("\\b" + range.firstLine + "\\b")).toBeTruthy();
expect($firstMatchRow.find(".line-text").text().match(range.pattern)).toBeTruthy();
var $lastMatchRow = $("#find-in-files-results tr[data-file-index='" + range.file + "'][data-item-index='" + range.last + "']");
expect($lastMatchRow.length).toBe(1);
expect($lastMatchRow.find(".line-number").text().match("\\b" + range.lastLine + "\\b")).toBeTruthy();
expect($lastMatchRow.find(".line-text").text().match(range.pattern)).toBeTruthy();
});
// Check enablement of buttons
expect($("#find-in-files-results .first-page").hasClass("disabled")).toBe(!options.firstPageEnabled);
expect($("#find-in-files-results .last-page").hasClass("disabled")).toBe(!options.lastPageEnabled);
expect($("#find-in-files-results .prev-page").hasClass("disabled")).toBe(!options.prevPageEnabled);
expect($("#find-in-files-results .next-page").hasClass("disabled")).toBe(!options.nextPageEnabled);
}
it("should page forward, then jump back to first page, displaying correct contents at each step", function () {
openProject(SpecRunnerUtils.getTestPath("/spec/FindReplace-test-files-manyhits"));
openSearchBar();
// This search will find 500 hits in 2 files. Since there are 100 hits per page, there should
// be five pages, and the third page should have 50 results from the first file and 50 results
// from the second file.
executeSearch("find this");
runs(function () {
var i;
for (i = 0; i < 5; i++) {
if (i > 0) {
$("#find-in-files-results .next-page").click();
}
expectPageDisplay(expectedPages[i]);
}
$("#find-in-files-results .first-page").click();
expectPageDisplay(expectedPages[0]);
});
});
it("should jump to last page, then page backward, displaying correct contents at each step", function () {
openProject(SpecRunnerUtils.getTestPath("/spec/FindReplace-test-files-manyhits"));
openSearchBar();
executeSearch("find this");
runs(function () {
var i;
$("#find-in-files-results .last-page").click();
for (i = 4; i >= 0; i--) {
if (i < 4) {
$("#find-in-files-results .prev-page").click();
}
expectPageDisplay(expectedPages[i]);
}
});
});
});
describe("SearchModel update on change events", function () {
var oldResults, gotChange, wasQuickChange;
function fullTestPath(path) {
return testPath + "/" + path;
}
function expectUnchangedExcept(paths) {
Object.keys(FindInFiles.searchModel.results).forEach(function (path) {
if (paths.indexOf(path) === -1) {
expect(FindInFiles.searchModel.results[path]).toEqual(oldResults[path]);
}
});
}
beforeEach(function () {
gotChange = false;
oldResults = null;
wasQuickChange = false;
$(FindInFiles.searchModel).on("change.FindInFilesTest", function (event, quickChange) {
gotChange = true;
wasQuickChange = quickChange;
});
openTestProjectCopy(defaultSourcePath);
doSearch({
queryInfo: {query: "foo"},
numMatches: 14
});
runs(function () {
oldResults = _.cloneDeep(FindInFiles.searchModel.results);
});
});
afterEach(function () {
$(FindInFiles.searchModel).off(".FindInFilesTest");
waitsForDone(CommandManager.execute(Commands.FILE_CLOSE_ALL, { _forceClose: true }), "close all files");
});
describe("when filename changes", function () {
it("should handle a filename change", function () {
runs(function () {
FindInFiles._fileNameChangeHandler(null, fullTestPath("foo.html"), fullTestPath("newfoo.html"));
});
waitsFor(function () { return gotChange; }, "model change event");
runs(function () {
expectUnchangedExcept([fullTestPath("foo.html"), fullTestPath("newfoo.html")]);
expect(FindInFiles.searchModel.results[fullTestPath("foo.html")]).toBeUndefined();
expect(FindInFiles.searchModel.results[fullTestPath("newfoo.html")]).toEqual(oldResults[fullTestPath("foo.html")]);
expect(FindInFiles.searchModel.countFilesMatches()).toEqual({files: 3, matches: 14});
expect(wasQuickChange).toBeFalsy();
});
});
it("should handle a folder change", function () {
runs(function () {
FindInFiles._fileNameChangeHandler(null, fullTestPath("css"), fullTestPath("newcss"));
});
waitsFor(function () { return gotChange; }, "model change event");
runs(function () {
expectUnchangedExcept([fullTestPath("css/foo.css"), fullTestPath("newcss/foo.css")]);
expect(FindInFiles.searchModel.results[fullTestPath("css/foo.css")]).toBeUndefined();
expect(FindInFiles.searchModel.results[fullTestPath("newcss/foo.css")]).toEqual(oldResults[fullTestPath("css/foo.css")]);
expect(FindInFiles.searchModel.countFilesMatches()).toEqual({files: 3, matches: 14});
expect(wasQuickChange).toBeFalsy();
});
});
});
describe("when in-memory document changes", function () {
it("should update the results when a matching line is added, updating line numbers and adding the match", function () {
runs(function () {
waitsForDone(CommandManager.execute(Commands.FILE_ADD_TO_WORKING_SET, { fullPath: fullTestPath("foo.html") }));
});
runs(function () {
var doc = DocumentManager.getOpenDocumentForPath(fullTestPath("foo.html")),
i;
expect(doc).toBeTruthy();
// Insert another line containing "foo" immediately above the second "foo" match.
doc.replaceRange("this is a foo instance\n", {line: 5, ch: 0});
// This should update synchronously.
expect(gotChange).toBe(true);
var oldFileResults = oldResults[fullTestPath("foo.html")],
newFileResults = FindInFiles.searchModel.results[fullTestPath("foo.html")];
// First match should be unchanged.
expect(newFileResults.matches[0]).toEqual(oldFileResults.matches[0]);
// Next match should be the new match. We just check the offsets here, not everything in the match record.
expect(newFileResults.matches[1].start).toEqual({line: 5, ch: 10});
expect(newFileResults.matches[1].end).toEqual({line: 5, ch: 13});
// Rest of the matches should have had their lines adjusted.
for (i = 2; i < newFileResults.matches.length; i++) {
var newMatch = newFileResults.matches[i],
oldMatch = oldFileResults.matches[i - 1];
expect(newMatch.start).toEqual({line: oldMatch.start.line + 1, ch: oldMatch.start.ch});
expect(newMatch.end).toEqual({line: oldMatch.end.line + 1, ch: oldMatch.end.ch});
}
// There should be one new match.
expect(FindInFiles.searchModel.countFilesMatches()).toEqual({files: 3, matches: 15});
// Make sure the model is adding the flag that will make the view debounce changes.
expect(wasQuickChange).toBeTruthy();
});
});
it("should update the results when a matching line is deleted, updating line numbers and removing the match", function () {
runs(function () {
waitsForDone(CommandManager.execute(Commands.FILE_ADD_TO_WORKING_SET, { fullPath: fullTestPath("foo.html") }));
});
runs(function () {
var doc = DocumentManager.getOpenDocumentForPath(fullTestPath("foo.html")),
i;
expect(doc).toBeTruthy();
// Remove the second "foo" match.
doc.replaceRange("", {line: 5, ch: 0}, {line: 6, ch: 0});
// This should update synchronously.
expect(gotChange).toBe(true);
var oldFileResults = oldResults[fullTestPath("foo.html")],
newFileResults = FindInFiles.searchModel.results[fullTestPath("foo.html")];
// First match should be unchanged.
expect(newFileResults.matches[0]).toEqual(oldFileResults.matches[0]);
// Second match should be deleted. The rest of the matches should have their lines adjusted.
for (i = 1; i < newFileResults.matches.length; i++) {
var newMatch = newFileResults.matches[i],
oldMatch = oldFileResults.matches[i + 1];
expect(newMatch.start).toEqual({line: oldMatch.start.line - 1, ch: oldMatch.start.ch});
expect(newMatch.end).toEqual({line: oldMatch.end.line - 1, ch: oldMatch.end.ch});
}
// There should be one fewer match.
expect(FindInFiles.searchModel.countFilesMatches()).toEqual({files: 3, matches: 13});
// Make sure the model is adding the flag that will make the view debounce changes.
expect(wasQuickChange).toBeTruthy();
});
});
it("should replace matches in a portion of the document that was edited to include a new match", function () {
runs(function () {
waitsForDone(CommandManager.execute(Commands.FILE_ADD_TO_WORKING_SET, { fullPath: fullTestPath("foo.html") }));
});
runs(function () {
var doc = DocumentManager.getOpenDocumentForPath(fullTestPath("foo.html")),
i;
expect(doc).toBeTruthy();
// Replace the second and third foo matches (on two adjacent lines) with a single foo match on a single line.
doc.replaceRange("this is a new foo match\n", {line: 5, ch: 0}, {line: 7, ch: 0});
// This should update synchronously.
expect(gotChange).toBe(true);
var oldFileResults = oldResults[fullTestPath("foo.html")],
newFileResults = FindInFiles.searchModel.results[fullTestPath("foo.html")];
// First match should be unchanged.
expect(newFileResults.matches[0]).toEqual(oldFileResults.matches[0]);
// Second match should be changed to reflect the new position.
expect(newFileResults.matches[1].start).toEqual({line: 5, ch: 14});
expect(newFileResults.matches[1].end).toEqual({line: 5, ch: 17});
// Third match should be deleted. The rest of the matches should have their lines adjusted.
for (i = 2; i < newFileResults.matches.length; i++) {
var newMatch = newFileResults.matches[i],
oldMatch = oldFileResults.matches[i + 1];
expect(newMatch.start).toEqual({line: oldMatch.start.line - 1, ch: oldMatch.start.ch});
expect(newMatch.end).toEqual({line: oldMatch.end.line - 1, ch: oldMatch.end.ch});
}
// There should be one fewer match.
expect(FindInFiles.searchModel.countFilesMatches()).toEqual({files: 3, matches: 13});
// Make sure the model is adding the flag that will make the view debounce changes.
expect(wasQuickChange).toBeTruthy();
});
});
it("should completely remove the document from the results list if all matches in the document are deleted", function () {
runs(function () {
waitsForDone(CommandManager.execute(Commands.FILE_ADD_TO_WORKING_SET, { fullPath: fullTestPath("foo.html") }));
});
runs(function () {
var doc = DocumentManager.getOpenDocumentForPath(fullTestPath("foo.html")),
i;
expect(doc).toBeTruthy();
// Replace all matches and check that the entire file was removed from the results list.
doc.replaceRange("this will not match", {line: 4, ch: 0}, {line: 18, ch: 0});
// This should update synchronously.
expect(gotChange).toBe(true);
expect(FindInFiles.searchModel.results[fullTestPath("foo.html")]).toBeUndefined();
// There should be one fewer file and the matches for that file should be gone.
expect(FindInFiles.searchModel.countFilesMatches()).toEqual({files: 2, matches: 7});
// Make sure the model is adding the flag that will make the view debounce changes.
expect(wasQuickChange).toBeTruthy();
});
});
});
// Unfortunately, we can't easily mock file changes, so we just do them in a copy of the project.
// This set of tests isn't as thorough as it could be, because it's difficult to perform file
// ops that will exercise all possible scenarios of change events (e.g. change events with
// both added and removed files), and conversely it's difficult to mock all the filesystem stuff
// without doing a bunch of work. So this is really just a set of basic sanity tests to make
// sure that stuff being refactored between the change handler and the model doesn't break
// basic update functionality.
describe("when on-disk file or folder changes", function () {
it("should add matches for a new file", function () {
var newFilePath;
runs(function () {
newFilePath = fullTestPath("newfoo.html");
expect(FindInFiles.searchModel.results[newFilePath]).toBeFalsy();
waitsForDone(promisify(FileSystem.getFileForPath(newFilePath), "write", "this is a new foo match\n"), "add new file");
});
waitsFor(function () { return gotChange; }, "model change event");
runs(function () {
var newFileResults = FindInFiles.searchModel.results[newFilePath];
expect(newFileResults).toBeTruthy();
expect(newFileResults.matches.length).toBe(1);
expect(newFileResults.matches[0].start).toEqual({line: 0, ch: 14});
expect(newFileResults.matches[0].end).toEqual({line: 0, ch: 17});
// There should be one new file and match.
expect(FindInFiles.searchModel.countFilesMatches()).toEqual({files: 4, matches: 15});
});
});
it("should remove matches for a deleted file", function () {
runs(function () {
expect(FindInFiles.searchModel.results[fullTestPath("foo.html")]).toBeTruthy();
waitsForDone(promisify(FileSystem.getFileForPath(fullTestPath("foo.html")), "unlink"), "delete file");
});
waitsFor(function () { return gotChange; }, "model change event");
runs(function () {
expect(FindInFiles.searchModel.results[fullTestPath("foo.html")]).toBeFalsy();
// There should be one fewer file and the matches should be removed.
expect(FindInFiles.searchModel.countFilesMatches()).toEqual({files: 2, matches: 7});
});
});
it("should remove matches for a deleted folder", function () {
runs(function () {
expect(FindInFiles.searchModel.results[fullTestPath("css/foo.css")]).toBeTruthy();
waitsForDone(promisify(FileSystem.getFileForPath(fullTestPath("css")), "unlink"), "delete folder");
});
waitsFor(function () { return gotChange; }, "model change event");
runs(function () {
expect(FindInFiles.searchModel.results[fullTestPath("css/foo.css")]).toBeFalsy();
// There should be one fewer file and the matches should be removed.
expect(FindInFiles.searchModel.countFilesMatches()).toEqual({files: 2, matches: 11});
});
});
});
});
describe("Replace", function () {
function expectProjectToMatchKnownGood(kgFolder, lineEndings, filesToSkip) {
runs(function () {
var testRootPath = ProjectManager.getProjectRoot().fullPath,
kgRootPath = SpecRunnerUtils.getTestPath("/spec/FindReplace-known-goods/" + kgFolder + "/");
function compareKnownGoodToTestFile(kgContents, kgFilePath) {
var testFilePath = testRootPath + kgFilePath.slice(kgRootPath.length);
if (!filesToSkip || filesToSkip.indexOf(testFilePath) === -1) {
return promisify(FileSystem.getFileForPath(testFilePath), "read").then(function (testContents) {
if (lineEndings) {
kgContents = FileUtils.translateLineEndings(kgContents, lineEndings);
}
expect(testContents).toEqual(kgContents);
});
}