-
Notifications
You must be signed in to change notification settings - Fork 176
/
JsTsSensorTest.java
945 lines (830 loc) · 35.9 KB
/
JsTsSensorTest.java
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
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.javascript.eslint;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.gson.Gson;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.slf4j.event.Level;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultTextPointer;
import org.sonar.api.batch.fs.internal.DefaultTextRange;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.CheckFactory;
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.batch.rule.internal.NewActiveRule;
import org.sonar.api.batch.sensor.cache.ReadCache;
import org.sonar.api.batch.sensor.cache.WriteCache;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.batch.sensor.issue.Issue;
import org.sonar.api.batch.sensor.issue.IssueLocation;
import org.sonar.api.batch.sensor.issue.internal.DefaultNoSonarFilter;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.DefaultTempFolder;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.FileLinesContext;
import org.sonar.api.measures.FileLinesContextFactory;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.testfixtures.log.LogTesterJUnit5;
import org.sonar.api.utils.TempFolder;
import org.sonar.api.utils.Version;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.javascript.checks.CheckList;
import org.sonar.plugins.javascript.TestUtils;
import org.sonar.plugins.javascript.eslint.BridgeServer.AnalysisResponse;
import org.sonar.plugins.javascript.eslint.BridgeServer.JsAnalysisRequest;
import org.sonar.plugins.javascript.eslint.BridgeServer.ParsingErrorCode;
import org.sonar.plugins.javascript.eslint.BridgeServer.TsProgram;
import org.sonar.plugins.javascript.eslint.BridgeServer.TsProgramRequest;
import org.sonar.plugins.javascript.eslint.cache.CacheTestUtils;
class JsTsSensorTest {
private static final String ESLINT_BASED_RULE = "S3923";
@RegisterExtension
public LogTesterJUnit5 logTester = new LogTesterJUnit5().setLevel(Level.DEBUG);
@TempDir
Path baseDir;
@Mock
private BridgeServerImpl bridgeServerMock;
private final TestAnalysisWarnings analysisWarnings = new TestAnalysisWarnings();
@Mock
private FileLinesContextFactory fileLinesContextFactory;
private SensorContextTester context;
@TempDir
Path tempDir;
TempFolder tempFolder;
@TempDir
Path workDir;
private Monitoring monitoring;
private AnalysisProcessor processAnalysis;
@BeforeEach
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
// reset is required as this static value might be set by another test
PluginInfo.setUcfgPluginVersion(null);
tempFolder = new DefaultTempFolder(tempDir.toFile(), true);
when(bridgeServerMock.isAlive()).thenReturn(true);
when(bridgeServerMock.analyzeTypeScript(any())).thenReturn(new AnalysisResponse());
when(bridgeServerMock.getCommandInfo()).thenReturn("bridgeServerMock command info");
when(bridgeServerMock.loadTsConfig(any()))
.thenAnswer(invocationOnMock -> {
String tsConfigPath = (String) invocationOnMock.getArguments()[0];
FilePredicates predicates = context.fileSystem().predicates();
List<String> files = StreamSupport
.stream(
context.fileSystem().inputFiles(predicates.hasLanguage("ts")).spliterator(),
false
)
.map(file -> file.absolutePath())
.collect(Collectors.toList());
return new TsConfigFile(tsConfigPath, files, emptyList());
});
when(bridgeServerMock.createTsConfigFile(any()))
.thenReturn(
new TsConfigFile(tempFolder.newFile().getAbsolutePath(), emptyList(), emptyList())
);
context = createSensorContext(baseDir);
context.setPreviousCache(mock(ReadCache.class));
context.setNextCache(mock(WriteCache.class));
FileLinesContext fileLinesContext = mock(FileLinesContext.class);
when(fileLinesContextFactory.createFor(any(InputFile.class))).thenReturn(fileLinesContext);
monitoring = new Monitoring(new MapSettings().asConfig());
processAnalysis =
new AnalysisProcessor(new DefaultNoSonarFilter(), fileLinesContextFactory, monitoring);
}
@Test
void should_have_descriptor() throws Exception {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor();
createSensor().describe(descriptor);
assertThat(descriptor.name()).isEqualTo("JavaScript/TypeScript analysis");
assertThat(descriptor.languages()).containsOnly("js", "ts");
}
@Test
void should_analyse() throws Exception {
AnalysisResponse expectedResponse = createResponse();
when(bridgeServerMock.analyzeTypeScript(any())).thenReturn(expectedResponse);
JsTsSensor sensor = createSensor();
DefaultInputFile inputFile = createInputFile(context);
createVueInputFile();
createTsConfigFile();
sensor.execute(context);
verify(bridgeServerMock, times(1)).initLinter(any(), any(), any(), any());
assertThat(context.allIssues()).hasSize(expectedResponse.issues.size());
assertThat(logTester.logs(LoggerLevel.DEBUG))
.contains(
String.format(
"Saving issue for rule no-all-duplicated-branches on file %s at line 1",
inputFile.absolutePath()
)
);
Iterator<Issue> issues = context.allIssues().iterator();
Issue firstIssue = issues.next();
Issue secondIssue = issues.next();
IssueLocation location = firstIssue.primaryLocation();
assertThat(location.inputComponent()).isEqualTo(inputFile);
assertThat(location.message()).isEqualTo("Issue message");
assertThat(location.textRange())
.isEqualTo(new DefaultTextRange(new DefaultTextPointer(1, 2), new DefaultTextPointer(3, 4)));
location = secondIssue.primaryLocation();
assertThat(location.inputComponent()).isEqualTo(inputFile);
assertThat(location.message()).isEqualTo("Line issue message");
assertThat(location.textRange())
.isEqualTo(new DefaultTextRange(new DefaultTextPointer(1, 0), new DefaultTextPointer(1, 9)));
assertThat(firstIssue.ruleKey().rule()).isEqualTo("S3923");
assertThat(secondIssue.ruleKey().rule()).isEqualTo("S3923");
assertThat(context.highlightingTypeAt(inputFile.key(), 1, 0)).isNotEmpty();
assertThat(context.highlightingTypeAt(inputFile.key(), 1, 0).get(0))
.isEqualTo(TypeOfText.KEYWORD);
assertThat(context.highlightingTypeAt(inputFile.key(), 2, 1)).isNotEmpty();
assertThat(context.highlightingTypeAt(inputFile.key(), 2, 1).get(0))
.isEqualTo(TypeOfText.CONSTANT);
assertThat(context.highlightingTypeAt(inputFile.key(), 3, 0)).isEmpty();
Collection<TextRange> symbols = context.referencesForSymbolAt(inputFile.key(), 1, 3);
assertThat(symbols).hasSize(1);
assertThat(symbols.iterator().next())
.isEqualTo(new DefaultTextRange(new DefaultTextPointer(2, 1), new DefaultTextPointer(2, 5)));
assertThat(context.measure(inputFile.key(), CoreMetrics.FUNCTIONS).value()).isEqualTo(1);
assertThat(context.measure(inputFile.key(), CoreMetrics.STATEMENTS).value()).isEqualTo(2);
assertThat(context.measure(inputFile.key(), CoreMetrics.CLASSES).value()).isEqualTo(3);
assertThat(context.measure(inputFile.key(), CoreMetrics.NCLOC).value()).isEqualTo(3);
assertThat(context.measure(inputFile.key(), CoreMetrics.COMMENT_LINES).value()).isEqualTo(3);
assertThat(context.measure(inputFile.key(), CoreMetrics.COMPLEXITY).value()).isEqualTo(4);
assertThat(context.measure(inputFile.key(), CoreMetrics.COGNITIVE_COMPLEXITY).value())
.isEqualTo(5);
assertThat(context.cpdTokens(inputFile.key())).hasSize(2);
}
@Test
void should_not_explode_if_no_response() throws Exception {
createVueInputFile();
when(bridgeServerMock.analyzeTypeScript(any())).thenThrow(new IOException("error"));
JsTsSensor sensor = createSensor();
DefaultInputFile inputFile = createInputFile(context);
sensor.execute(context);
assertThat(logTester.logs(LoggerLevel.ERROR))
.contains("Failed to get response while analyzing " + inputFile.uri());
assertThat(context.allIssues()).isEmpty();
}
private SensorContextTester createSensorContext(Path baseDir) throws IOException {
SensorContextTester ctx = null;
if (isWindows()) {
// toRealPath avoids 8.3 paths on Windows, which clashes with tests where test file location is checked
// https://en.wikipedia.org/wiki/8.3_filename
ctx = SensorContextTester.create(baseDir.toRealPath());
} else {
ctx = SensorContextTester.create(baseDir);
}
ctx.fileSystem().setWorkDir(workDir);
ctx.setNextCache(mock(WriteCache.class));
ctx.setPreviousCache(mock(ReadCache.class));
return ctx;
}
@Test
void should_raise_a_parsing_error() throws IOException {
setSonarLintRuntime(context);
createTsConfigFile();
when(bridgeServerMock.analyzeTypeScript(any()))
.thenReturn(
new Gson()
.fromJson(
"{ parsingError: { line: 3, message: \"Parse error message\", code: \"Parsing\"} }",
AnalysisResponse.class
)
);
createInputFile(context);
createSensor().execute(context);
Collection<Issue> issues = context.allIssues();
assertThat(issues).hasSize(1);
Issue issue = issues.iterator().next();
assertThat(issue.primaryLocation().textRange().start().line()).isEqualTo(3);
assertThat(issue.primaryLocation().message()).isEqualTo("Parse error message");
assertThat(context.allAnalysisErrors()).hasSize(1);
assertThat(logTester.logs(LoggerLevel.ERROR))
.contains("Failed to parse file [dir/file.ts] at line 3: Parse error message");
}
@Test
void should_raise_a_parsing_error_without_line() throws IOException {
createVueInputFile();
when(bridgeServerMock.analyzeTypeScript(any()))
.thenReturn(
new Gson()
.fromJson("{ parsingError: { message: \"Parse error message\"} }", AnalysisResponse.class)
);
createInputFile(context);
createSensor().execute(context);
Collection<Issue> issues = context.allIssues();
assertThat(issues).hasSize(2);
Issue issue = issues.iterator().next();
assertThat(issue.primaryLocation().textRange()).isNull(); // file level issueCheckListTest.testTypeScriptChecks
assertThat(issue.primaryLocation().message()).isEqualTo("Parse error message");
assertThat(context.allAnalysisErrors()).hasSize(2);
assertThat(logTester.logs(LoggerLevel.ERROR))
.contains(
"Failed to analyze file [dir/file.ts]: Parse error message",
"Failed to analyze file [file.vue]: Parse error message"
);
}
@Test
void should_send_content_on_sonarlint() throws Exception {
SensorContextTester ctx = createSensorContext(baseDir);
setSonarLintRuntime(ctx);
DefaultInputFile file = createInputFile(ctx);
Files.write(baseDir.resolve("tsconfig.json"), singleton("{}"));
when(bridgeServerMock.loadTsConfig(any()))
.thenReturn(
new TsConfigFile("tsconfig.json", singletonList(file.absolutePath()), emptyList())
);
ArgumentCaptor<JsAnalysisRequest> captor = ArgumentCaptor.forClass(JsAnalysisRequest.class);
createSensor().execute(ctx);
verify(bridgeServerMock).analyzeTypeScript(captor.capture());
assertThat(captor.getValue().fileContent)
.isEqualTo("if (cond)\n" + "doFoo(); \n" + "else \n" + "doFoo();");
}
@Test
void should_not_send_content() throws Exception {
var ctx = createSensorContext(baseDir);
var inputFile = createInputFile(ctx);
var tsProgram = new TsProgram("1", List.of(inputFile.absolutePath()), List.of());
when(bridgeServerMock.createProgram(any())).thenReturn(tsProgram);
when(bridgeServerMock.analyzeTypeScript(any())).thenReturn(new AnalysisResponse());
createTsConfigFile();
createSensor().execute(ctx);
var captor = ArgumentCaptor.forClass(JsAnalysisRequest.class);
verify(bridgeServerMock).analyzeTypeScript(captor.capture());
assertThat(captor.getValue().fileContent).isNull();
var deleteCaptor = ArgumentCaptor.forClass(TsProgram.class);
verify(bridgeServerMock).deleteProgram(deleteCaptor.capture());
assertThat(deleteCaptor.getValue().programId).isEqualTo(tsProgram.programId);
}
@Test
void should_send_content_when_not_utf8() throws Exception {
SensorContextTester ctx = createSensorContext(baseDir);
createVueInputFile(ctx);
String content = "if (cond)\ndoFoo(); \nelse \ndoFoo();";
DefaultInputFile inputFile = new TestInputFileBuilder("moduleKey", "dir/file.ts")
.setLanguage("ts")
.setCharset(StandardCharsets.ISO_8859_1)
.setContents(content)
.build();
ctx.fileSystem().add(inputFile);
Files.write(baseDir.resolve("tsconfig.json"), singleton("{}"));
when(bridgeServerMock.loadTsConfig(any()))
.thenReturn(
new TsConfigFile("tsconfig.json", singletonList(inputFile.absolutePath()), emptyList())
);
ArgumentCaptor<JsAnalysisRequest> captor = ArgumentCaptor.forClass(JsAnalysisRequest.class);
createSensor().execute(ctx);
verify(bridgeServerMock, times(2)).analyzeTypeScript(captor.capture());
assertThat(captor.getAllValues()).extracting(c -> c.fileContent).contains(content);
}
@Test
void should_log_when_failing_typescript() throws Exception {
AnalysisResponse parseError = new AnalysisResponse();
parseError.parsingError = new BridgeServer.ParsingError();
parseError.parsingError.message = "Debug Failure. False expression.";
parseError.parsingError.code = ParsingErrorCode.FAILING_TYPESCRIPT;
when(bridgeServerMock.analyzeTypeScript(any())).thenReturn(parseError);
var file1 = createInputFile(context, "dir/file1.ts");
var file2 = createInputFile(context, "dir/file2.ts");
var tsConfigFile = new TsConfigFile(
"tsconfig.json",
List.of(file1.absolutePath(), file2.absolutePath()),
emptyList()
);
when(bridgeServerMock.loadTsConfig(any())).thenReturn(tsConfigFile);
createVueInputFile();
createSensor().execute(context);
assertThat(logTester.logs(LoggerLevel.ERROR))
.contains(
"Failed to analyze file [dir/file1.ts] from TypeScript: Debug Failure. False expression."
);
assertThat(logTester.logs(LoggerLevel.ERROR))
.contains(
"Failed to analyze file [dir/file2.ts] from TypeScript: Debug Failure. False expression."
);
}
@Test
void should_analyze_by_tsconfig() throws Exception {
Path baseDir = Paths.get("src/test/resources/multi-tsconfig");
SensorContextTester context = createSensorContext(baseDir);
setSonarLintRuntime(context);
DefaultInputFile file1 = inputFileFromResource(context, baseDir, "dir1/file.ts");
DefaultInputFile file2 = inputFileFromResource(context, baseDir, "dir2/file.ts");
DefaultInputFile file3 = inputFileFromResource(context, baseDir, "dir3/file.ts");
var noconfig = inputFileFromResource(context, baseDir, "noconfig.ts");
String tsconfig1 = absolutePath(baseDir, "dir1/tsconfig.json");
when(bridgeServerMock.loadTsConfig(tsconfig1))
.thenReturn(new TsConfigFile(tsconfig1, singletonList(file1.absolutePath()), emptyList()));
String tsconfig2 = absolutePath(baseDir, "dir2/tsconfig.json");
when(bridgeServerMock.loadTsConfig(tsconfig2))
.thenReturn(new TsConfigFile(tsconfig2, singletonList(file2.absolutePath()), emptyList()));
String tsconfig3 = absolutePath(baseDir, "dir3/tsconfig.json");
when(bridgeServerMock.loadTsConfig(tsconfig3))
.thenReturn(new TsConfigFile(tsconfig3, singletonList(file3.absolutePath()), emptyList()));
ArgumentCaptor<JsAnalysisRequest> captor = ArgumentCaptor.forClass(JsAnalysisRequest.class);
createSensor().execute(context);
verify(bridgeServerMock, times(4)).analyzeTypeScript(captor.capture());
assertThat(captor.getAllValues())
.extracting(req -> req.filePath)
.containsExactlyInAnyOrder(
file1.absolutePath(),
file2.absolutePath(),
file3.absolutePath(),
noconfig.absolutePath()
);
verify(bridgeServerMock, times(4)).newTsConfig();
}
@Test
void should_analyze_by_program_on_missing_extended_tsconfig() throws Exception {
Path baseDir = Paths.get("src/test/resources/external-tsconfig").toAbsolutePath();
SensorContextTester context = createSensorContext(baseDir);
DefaultInputFile file1 = inputFileFromResource(context, baseDir, "src/main.ts");
String tsconfig = absolutePath(baseDir, "tsconfig.json");
when(bridgeServerMock.createProgram(any()))
.thenReturn(
new TsProgram(
"1",
Arrays.asList(file1.absolutePath(), "not/part/sonar/project/file.ts"),
emptyList(),
true
)
);
when(bridgeServerMock.analyzeTypeScript(any())).thenReturn(new AnalysisResponse());
ArgumentCaptor<JsAnalysisRequest> captor = ArgumentCaptor.forClass(JsAnalysisRequest.class);
createSensor().execute(context);
verify(bridgeServerMock, times(1)).analyzeTypeScript(captor.capture());
assertThat(captor.getAllValues())
.extracting(req -> req.filePath)
.containsExactlyInAnyOrder(file1.absolutePath());
verify(bridgeServerMock, times(1)).deleteProgram(any());
assertThat(logTester.logs(LoggerLevel.WARN))
.contains(
"At least one tsconfig.json was not found in the project. Please run 'npm install' for a more complete analysis. Check analysis logs for more details."
);
assertThat(analysisWarnings.warnings)
.contains(
"At least one tsconfig.json was not found in the project. Please run 'npm install' for a more complete analysis. Check analysis logs for more details."
);
}
@Test
void should_analyze_by_program() throws Exception {
Path baseDir = Paths.get("src/test/resources/multi-tsconfig").toAbsolutePath();
SensorContextTester context = createSensorContext(baseDir);
var file1 = inputFileFromResource(context, baseDir, "dir1/file.ts");
var file2 = inputFileFromResource(context, baseDir, "dir2/file.ts");
var file3 = inputFileFromResource(context, baseDir, "dir3/file.ts");
var noconfig = inputFileFromResource(context, baseDir, "noconfig.ts");
String tsconfig1 = absolutePath(baseDir, "dir1/tsconfig.json");
when(bridgeServerMock.createProgram(any()))
.thenReturn(
new TsProgram(
"1",
Arrays.asList(file1.absolutePath(), "not/part/sonar/project/file.ts"),
emptyList()
),
new TsProgram(
"2",
singletonList(file2.absolutePath()),
singletonList("some-other-tsconfig.json")
),
new TsProgram("something went wrong"),
new TsProgram(
"3",
Arrays.asList(file2.absolutePath(), file3.absolutePath()),
singletonList(tsconfig1)
)
);
when(bridgeServerMock.analyzeTypeScript(any())).thenReturn(new AnalysisResponse());
ArgumentCaptor<JsAnalysisRequest> captor = ArgumentCaptor.forClass(JsAnalysisRequest.class);
createSensor().execute(context);
verify(bridgeServerMock, times(4)).analyzeTypeScript(captor.capture());
assertThat(captor.getAllValues())
.extracting(req -> req.filePath)
.containsExactlyInAnyOrder(
file1.absolutePath(),
file2.absolutePath(),
file3.absolutePath(),
noconfig.absolutePath()
);
verify(bridgeServerMock, times(3)).deleteProgram(any());
assertThat(logTester.logs(LoggerLevel.DEBUG))
.contains(
"File already analyzed: '" +
file2.absolutePath() +
"'. Check your project configuration to avoid files being part of multiple projects."
);
assertThat(logTester.logs(LoggerLevel.ERROR))
.contains("Failed to create program: something went wrong");
}
@Test
void should_not_analyze_references_twice() throws Exception {
Path baseDir = Paths.get("src/test/resources/referenced-tsconfigs").toAbsolutePath();
SensorContextTester context = createSensorContext(baseDir);
DefaultInputFile file1 = inputFileFromResource(context, baseDir, "file.ts");
DefaultInputFile file2 = inputFileFromResource(context, baseDir, "dir/file.ts");
String tsconfig1 = absolutePath(baseDir, "tsconfig.json");
String tsconfig2 = absolutePath(baseDir, "dir/tsconfig.json");
when(bridgeServerMock.createProgram(any()))
.thenReturn(
new TsProgram(
"1",
singletonList(file1.absolutePath()),
singletonList(tsconfig2.replaceAll("[\\\\/]", "/"))
),
new TsProgram(
"2",
singletonList(file2.absolutePath()),
singletonList(tsconfig1.replaceAll("[\\\\/]", "/"))
)
);
when(bridgeServerMock.analyzeTypeScript(any())).thenReturn(new AnalysisResponse());
ArgumentCaptor<TsProgramRequest> captorProgram = ArgumentCaptor.forClass(
TsProgramRequest.class
);
createSensor().execute(context);
verify(bridgeServerMock, times(2)).createProgram(captorProgram.capture());
assertThat(captorProgram.getAllValues())
.extracting(req -> req.tsConfig)
.isEqualTo(List.of(tsconfig1, tsconfig2));
verify(bridgeServerMock, times(2)).deleteProgram(any());
assertThat(logTester.logs(LoggerLevel.INFO))
.containsOnlyOnce("TypeScript configuration file " + tsconfig1);
assertThat(logTester.logs(LoggerLevel.INFO))
.containsOnlyOnce("TypeScript configuration file " + tsconfig2);
}
// This test will be removed when logic is moved to Node
@Test
@Disabled
void should_do_nothing_when_no_tsconfig_when_analysis_with_program() throws IOException {
var ctx = createSensorContext(baseDir);
createInputFile(ctx);
createSensor().execute(ctx);
assertThat(logTester.logs(LoggerLevel.INFO)).contains("No tsconfig.json file found");
assertThat(logTester.logs(LoggerLevel.INFO))
.contains(
"Skipped 1 file(s) because they were not part of any tsconfig.json (enable debug logs to see the full list)"
);
assertThat(logTester.logs(LoggerLevel.DEBUG))
.contains("File not part of any tsconfig.json: dir/file.ts");
}
@Test
void should_resolve_project_references_from_tsconfig() throws Exception {
Path baseDir = Paths.get("src/test/resources/solution-tsconfig");
SensorContextTester context = createSensorContext(baseDir);
setSonarLintRuntime(context);
DefaultInputFile file1 = inputFileFromResource(context, baseDir, "src/file.ts");
String tsconfig = absolutePath(baseDir, "tsconfig.json");
String appTsConfig = "src/tsconfig.app.json";
String appTsConfig2 = "src/tsconfig.app2.json";
// we intentionally create cycle between appTsConfig and appTsConfig2
when(bridgeServerMock.loadTsConfig(anyString()))
.thenReturn(
new TsConfigFile(tsconfig, emptyList(), singletonList(appTsConfig)),
new TsConfigFile(
appTsConfig,
singletonList(file1.absolutePath()),
singletonList(appTsConfig2)
),
new TsConfigFile(
appTsConfig2,
singletonList(file1.absolutePath()),
singletonList(appTsConfig)
)
);
ArgumentCaptor<JsAnalysisRequest> captor = ArgumentCaptor.forClass(JsAnalysisRequest.class);
createSensor().execute(context);
verify(bridgeServerMock, times(3)).loadTsConfig(anyString());
verify(bridgeServerMock, times(1)).analyzeTypeScript(captor.capture());
assertThat(captor.getAllValues())
.extracting(req -> req.filePath)
.containsExactlyInAnyOrder(file1.absolutePath());
}
private String absolutePath(Path baseDir, String relativePath) {
return new File(baseDir.toFile(), relativePath).getAbsolutePath();
}
private DefaultInputFile inputFileFromResource(
SensorContextTester context,
Path baseDir,
String file
) throws IOException {
Path filePath = baseDir.resolve(file);
DefaultInputFile inputFile = new TestInputFileBuilder(
"projectKey",
baseDir.toFile(),
filePath.toFile()
)
.setContents(Files.readString(filePath))
.setCharset(StandardCharsets.UTF_8)
.setLanguage("ts")
.build();
context.fileSystem().add(inputFile);
return inputFile;
}
@Test
void should_stop_when_no_input_files() throws Exception {
SensorContextTester context = createSensorContext(tempDir);
createSensor().execute(context);
assertThat(logTester.logs())
.contains(
"No input files found for analysis",
"Hit the cache for 0 out of 0",
"Miss the cache for 0 out of 0"
);
}
@Test
void should_fail_fast() throws Exception {
createTsConfigFile();
when(bridgeServerMock.analyzeTypeScript(any())).thenThrow(new IOException("error"));
JsTsSensor sensor = createSensor();
MapSettings settings = new MapSettings().setProperty("sonar.internal.analysis.failFast", true);
context.setSettings(settings);
createInputFile(context);
assertThatThrownBy(() -> sensor.execute(context))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Analysis failed (\"sonar.internal.analysis.failFast\"=true)");
}
@Test
void should_fail_fast_with_parsing_error_without_line() throws IOException {
createVueInputFile();
when(bridgeServerMock.analyzeTypeScript(any()))
.thenReturn(
new Gson()
.fromJson("{ parsingError: { message: \"Parse error message\"} }", AnalysisResponse.class)
);
MapSettings settings = new MapSettings().setProperty("sonar.internal.analysis.failFast", true);
context.setSettings(settings);
createInputFile(context);
assertThatThrownBy(() -> createSensor().execute(context))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Analysis failed (\"sonar.internal.analysis.failFast\"=true)");
assertThat(logTester.logs(LoggerLevel.ERROR))
.contains("Failed to analyze file [dir/file.ts]: Parse error message");
}
@Test
void stop_analysis_if_server_is_not_responding() throws Exception {
when(bridgeServerMock.isAlive()).thenReturn(false);
JsTsSensor sensor = createSensor();
createTsConfigFile();
createVueInputFile();
createInputFile(context);
sensor.execute(context);
final var logAndArguments = logTester.getLogs(Level.ERROR).get(0);
assertThat(logAndArguments.getFormattedMsg())
.isEqualTo("Failure during analysis, bridgeServerMock command info");
assertThat(logAndArguments.getThrowable().getMessage())
.isEqualTo("the bridge server is not answering");
}
@Test
void stop_analysis_if_cancelled() throws Exception {
JsTsSensor sensor = createSensor();
createInputFile(context);
setSonarLintRuntime(context);
createTsConfigFile();
context.setCancelled(true);
sensor.execute(context);
assertThat(logTester.logs(LoggerLevel.INFO))
.contains(
"org.sonar.plugins.javascript.CancellationException: Analysis interrupted because the SensorContext is in cancelled state"
);
}
@Test
void log_debug_analyzed_filename_with_program() throws Exception {
JsTsSensor sensor = createSensor();
createTsConfigFile();
DefaultInputFile inputFile = createInputFile(context);
var tsProgram = new TsProgram("1", List.of(inputFile.absolutePath()), List.of());
when(bridgeServerMock.createProgram(any())).thenReturn(tsProgram);
when(bridgeServerMock.analyzeTypeScript(any())).thenReturn(new AnalysisResponse());
sensor.execute(context);
assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("Analyzing file: " + inputFile.uri());
}
@Test
void log_debug_analyzed_filename_with_tsconfig() throws Exception {
AnalysisResponse expectedResponse = createResponse();
when(bridgeServerMock.analyzeTypeScript(any())).thenReturn(expectedResponse);
JsTsSensor sensor = createSensor();
DefaultInputFile inputFile = createInputFile(context);
// having a vue file makes TypeScriptSensor#shouldAnalyzeWithProgram() return false, which leads to the path that executes TypeScript#analyze()
createVueInputFile();
createTsConfigFile();
sensor.execute(context);
assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("Analyzing file: " + inputFile.uri());
}
@Test
void should_save_cached_cpd() throws IOException {
var path = "dir/file.ts";
var context = CacheTestUtils.createContextWithCache(baseDir, workDir, path);
var file = TestUtils
.createInputFile(context, "if (cond)\ndoFoo(); \nelse \ndoFoo();", path)
.setStatus(InputFile.Status.SAME);
var sensor = createSensor();
createVueInputFile(context);
createTsConfigFile();
when(bridgeServerMock.loadTsConfig(any()))
.thenReturn(
new TsConfigFile("tsconfig.json", singletonList(file.absolutePath()), emptyList())
);
sensor.execute(context);
assertThat(context.cpdTokens(file.key())).hasSize(2);
assertThat(logTester.logs(LoggerLevel.DEBUG))
.contains("Processing cache analysis of file: " + file.uri());
}
@Test
void should_save_cached_cpd_with_program() throws IOException {
var path = "dir/file.ts";
var context = CacheTestUtils.createContextWithCache(baseDir, workDir, path);
var file = TestUtils
.createInputFile(context, "if (cond)\ndoFoo(); \nelse \ndoFoo();", path)
.setStatus(InputFile.Status.SAME);
var sensor = createSensor();
createTsConfigFile();
var tsProgram = new TsProgram("1", List.of(file.absolutePath()), List.of());
when(bridgeServerMock.createProgram(any())).thenReturn(tsProgram);
sensor.execute(context);
assertThat(context.cpdTokens(file.key())).hasSize(2);
assertThat(logTester.logs(LoggerLevel.DEBUG))
.contains("Processing cache analysis of file: " + file.uri());
}
private JsTsSensor createSensor() {
return new JsTsSensor(
checks(ESLINT_BASED_RULE, "S2260"),
bridgeServerMock,
analysisWarnings,
tempFolder,
monitoring,
analysisWithProgram(),
analysisWithWatchProgram()
);
}
private AnalysisWithProgram analysisWithProgram() {
return new AnalysisWithProgram(bridgeServerMock, monitoring, processAnalysis, analysisWarnings);
}
private AnalysisWithWatchProgram analysisWithWatchProgram() {
return new AnalysisWithWatchProgram(bridgeServerMock, monitoring, processAnalysis);
}
private AnalysisResponse createResponse() {
return new Gson()
.fromJson(
"{" +
createIssues() +
"," +
createHighlights() +
"," +
createMetrics() +
"," +
createCpdTokens() +
"," +
createHighlightedSymbols() +
"}",
AnalysisResponse.class
);
}
private String createIssues() {
return (
"issues: [{" +
"\"line\":1,\"column\":2,\"endLine\":3,\"endColumn\":4,\"ruleId\":\"no-all-duplicated-branches\",\"message\":\"Issue message\", \"secondaryLocations\": []}," +
"{\"line\":1,\"column\":1,\"ruleId\":\"no-all-duplicated-branches\",\"message\":\"Line issue message\", \"secondaryLocations\": []" +
"}]"
);
}
private String createHighlights() {
return (
"highlights: [" +
"{\"location\": { \"startLine\":1,\"startCol\":0,\"endLine\":1,\"endCol\":4},\"textType\":\"KEYWORD\"}," +
"{\"location\": { \"startLine\":2,\"startCol\":1,\"endLine\":2,\"endCol\":5},\"textType\":\"CONSTANT\"}" +
"]"
);
}
private String createHighlightedSymbols() {
return (
"highlightedSymbols: [{" +
"\"declaration\": {\"startLine\":1,\"startCol\":0,\"endLine\":1,\"endCol\":4}," +
"\"references\": [{\"startLine\":2,\"startCol\":1,\"endLine\":2,\"endCol\":5}]" +
"}]"
);
}
private String createMetrics() {
return (
"metrics: {" +
"\"ncloc\":[1, 2, 3]," +
"\"commentLines\":[4, 5, 6]," +
"\"nosonarLines\":[7, 8, 9]," +
"\"executableLines\":[10, 11, 12]," +
"\"functions\":1," +
"\"statements\":2," +
"\"classes\":3," +
"\"complexity\":4," +
"\"cognitiveComplexity\":5" +
"}"
);
}
private String createCpdTokens() {
return (
"cpdTokens: [" +
"{\"location\": { \"startLine\":1,\"startCol\":0,\"endLine\":1,\"endCol\":4},\"image\":\"LITERAL\"}," +
"{\"location\": { \"startLine\":2,\"startCol\":1,\"endLine\":2,\"endCol\":5},\"image\":\"if\"}" +
"]"
);
}
private DefaultInputFile createInputFile(SensorContextTester context) {
return createInputFile(context, "dir/file.ts");
}
private DefaultInputFile createInputFile(SensorContextTester context, String relativePath) {
DefaultInputFile inputFile = new TestInputFileBuilder(
"moduleKey",
baseDir.toFile(),
baseDir.resolve(relativePath).toFile()
)
.setLanguage("ts")
.setCharset(StandardCharsets.UTF_8)
.setContents("if (cond)\ndoFoo(); \nelse \ndoFoo();")
.build();
context.fileSystem().add(inputFile);
return inputFile;
}
private void createTsConfigFile() throws IOException {
Files.writeString(baseDir.resolve("tsconfig.json"), "{}");
}
private void createVueInputFile() {
createVueInputFile(context);
}
private void createVueInputFile(SensorContextTester context) {
var vueFile = new TestInputFileBuilder(
"moduleKey",
baseDir.toFile(),
baseDir.resolve("file.vue").toFile()
)
.setLanguage("js")
.setCharset(StandardCharsets.UTF_8)
.setContents("<script lang=\"ts\"></script>")
.build();
context.fileSystem().add(vueFile);
}
private void setSonarLintRuntime(SensorContextTester context) {
context.setRuntime(SonarRuntimeImpl.forSonarLint(Version.create(8, 9)));
}
private boolean isWindows() {
var osName = System.getProperty("os.name");
return osName.toLowerCase().startsWith("win");
}
private static JsTsChecks checks(String... ruleKeys) {
ActiveRulesBuilder builder = new ActiveRulesBuilder();
for (String ruleKey : ruleKeys) {
builder.addRule(
new NewActiveRule.Builder()
.setRuleKey(RuleKey.of(CheckList.TS_REPOSITORY_KEY, ruleKey))
.build()
);
}
return new JsTsChecks(new CheckFactory(builder.build()));
}
}