repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/CpdExecutorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.cpd;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.ArgumentMatchers;
import org.slf4j.event.Level;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.util.CloseableIterator;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.block.ByteArray;
import org.sonar.duplications.index.CloneGroup;
import org.sonar.duplications.index.ClonePart;
import org.sonar.scanner.cpd.index.SonarCpdBlockIndex;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReport.Duplicate;
import org.sonar.scanner.protocol.output.ScannerReport.Duplication;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.report.ReportPublisher;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class CpdExecutorTest {
@Rule
public LogTester logTester = new LogTester();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private CpdExecutor executor;
private final ExecutorService executorService = mock(ExecutorService.class);
private final CpdSettings settings = mock(CpdSettings.class);
private final ReportPublisher publisher = mock(ReportPublisher.class);
private final SonarRuntime sonarRuntime = mock(SonarRuntime.class);
private final SonarCpdBlockIndex index = new SonarCpdBlockIndex(publisher, settings);
private ScannerReportReader reader;
private DefaultInputFile batchComponent1;
private DefaultInputFile batchComponent2;
private DefaultInputFile batchComponent3;
private File baseDir;
private InputComponentStore componentStore;
@Before
public void setUp() throws IOException {
File outputDir = temp.newFolder();
FileStructure fileStructure = new FileStructure(outputDir);
baseDir = temp.newFolder();
when(publisher.getWriter()).thenReturn(new ScannerReportWriter(fileStructure));
DefaultInputProject project = TestInputFileBuilder.newDefaultInputProject("foo", baseDir);
componentStore = new InputComponentStore(mock(BranchConfiguration.class), sonarRuntime);
executor = new CpdExecutor(settings, index, publisher, componentStore, executorService);
reader = new ScannerReportReader(fileStructure);
batchComponent1 = createComponent("src/Foo.php", 5);
batchComponent2 = createComponent("src/Foo2.php", 5);
batchComponent3 = createComponent("src/Foo3.php", 5);
}
@Test
public void dont_fail_if_nothing_to_save() {
executor.saveDuplications(batchComponent1, Collections.emptyList());
assertThat(reader.readComponentDuplications(batchComponent1.scannerId())).isExhausted();
}
@Test
public void should_save_single_duplication() {
List<CloneGroup> groups = Collections.singletonList(newCloneGroup(
new ClonePart(batchComponent1.key(), 0, 2, 4),
new ClonePart(batchComponent2.key(), 0, 15, 17)));
executor.saveDuplications(batchComponent1, groups);
Duplication[] dups = readDuplications(1);
assertDuplication(dups[0], 2, 4, batchComponent2.scannerId(), 15, 17);
}
@Test
public void should_save_duplication_on_same_file() {
List<CloneGroup> groups = Collections.singletonList(newCloneGroup(
new ClonePart(batchComponent1.key(), 0, 5, 204),
new ClonePart(batchComponent1.key(), 0, 215, 414)));
executor.saveDuplications(batchComponent1, groups);
Duplication[] dups = readDuplications(1);
assertDuplication(dups[0], 5, 204, null, 215, 414);
}
@Test
public void should_limit_number_of_references() {
// 1 origin part + 101 duplicates = 102
List<ClonePart> parts = new ArrayList<>(CpdExecutor.MAX_CLONE_PART_PER_GROUP + 2);
for (int i = 0; i < CpdExecutor.MAX_CLONE_PART_PER_GROUP + 2; i++) {
parts.add(new ClonePart(batchComponent1.key(), i, i, i + 1));
}
List<CloneGroup> groups = Collections.singletonList(CloneGroup.builder().setLength(0).setOrigin(parts.get(0)).setParts(parts).build());
executor.saveDuplications(batchComponent1, groups);
Duplication[] dups = readDuplications(1);
assertThat(dups[0].getDuplicateList()).hasSize(CpdExecutor.MAX_CLONE_PART_PER_GROUP);
assertThat(logTester.logs(Level.WARN))
.contains("Too many duplication references on file " + batchComponent1 + " for block at line 0. Keep only the first "
+ CpdExecutor.MAX_CLONE_PART_PER_GROUP + " references.");
}
@Test
public void should_limit_number_of_clones() {
// 1 origin part + 101 duplicates = 102
List<CloneGroup> dups = new ArrayList<>(CpdExecutor.MAX_CLONE_GROUP_PER_FILE + 1);
for (int i = 0; i < CpdExecutor.MAX_CLONE_GROUP_PER_FILE + 1; i++) {
ClonePart clonePart = new ClonePart(batchComponent1.key(), i, i, i + 1);
ClonePart dupPart = new ClonePart(batchComponent1.key(), i + 1, i + 1, i + 2);
dups.add(newCloneGroup(clonePart, dupPart));
}
executor.saveDuplications(batchComponent1, dups);
assertThat(reader.readComponentDuplications(batchComponent1.scannerId())).toIterable().hasSize(CpdExecutor.MAX_CLONE_GROUP_PER_FILE);
assertThat(logTester.logs(Level.WARN))
.contains("Too many duplication groups on file " + batchComponent1 + ". Keep only the first " + CpdExecutor.MAX_CLONE_GROUP_PER_FILE + " groups.");
}
@Test
public void should_save_duplication_involving_three_files() {
List<CloneGroup> groups = Collections.singletonList(newCloneGroup(
new ClonePart(batchComponent1.key(), 0, 5, 204),
new ClonePart(batchComponent2.key(), 0, 15, 214),
new ClonePart(batchComponent3.key(), 0, 25, 224)));
executor.saveDuplications(batchComponent1, groups);
Duplication[] dups = readDuplications(1);
assertDuplication(dups[0], 5, 204, 2);
assertDuplicate(dups[0].getDuplicate(0), batchComponent2.scannerId(), 15, 214);
assertDuplicate(dups[0].getDuplicate(1), batchComponent3.scannerId(), 25, 224);
}
@Test
public void should_save_two_duplicated_groups_involving_three_files() {
List<CloneGroup> groups = Arrays.asList(
newCloneGroup(new ClonePart(batchComponent1.key(), 0, 5, 204),
new ClonePart(batchComponent2.key(), 0, 15, 214)),
newCloneGroup(new ClonePart(batchComponent1.key(), 0, 15, 214),
new ClonePart(batchComponent3.key(), 0, 15, 214)));
executor.saveDuplications(batchComponent1, groups);
Duplication[] dups = readDuplications(2);
assertDuplication(dups[0], 5, 204, batchComponent2.scannerId(), 15, 214);
assertDuplication(dups[1], 15, 214, batchComponent3.scannerId(), 15, 214);
}
@Test
public void should_ignore_missing_component() {
Block block = Block.builder()
.setBlockHash(new ByteArray("AAAABBBBCCCC"))
.setResourceId("unknown")
.build();
index.insert(batchComponent1, Collections.singletonList(block));
executor.execute();
verify(executorService).shutdown();
verifyNoMoreInteractions(executorService);
readDuplications(batchComponent1, 0);
assertThat(logTester.logs(Level.ERROR)).contains("Resource not found in component store: unknown. Skipping CPD computation for it");
}
@Test
public void should_timeout() {
Block block = Block.builder()
.setBlockHash(new ByteArray("AAAABBBBCCCC"))
.setResourceId(batchComponent1.key())
.build();
index.insert(batchComponent1, Collections.singletonList(block));
when(executorService.submit(ArgumentMatchers.any(Callable.class))).thenReturn(new CompletableFuture());
executor.execute(1);
readDuplications(0);
assertThat(logTester.logs(Level.WARN))
.usingElementComparator((l, r) -> l.matches(r) ? 0 : 1)
.containsOnly(
"Timeout during detection of duplications for .*Foo.php");
}
private DefaultInputFile createComponent(String relativePath, int lines) {
return createComponent(relativePath, lines, f -> {
});
}
private DefaultInputFile createComponent(String relativePath, int lines, Consumer<TestInputFileBuilder> config) {
TestInputFileBuilder fileBuilder = new TestInputFileBuilder("foo", relativePath)
.setModuleBaseDir(baseDir.toPath())
.setLines(lines);
config.accept(fileBuilder);
DefaultInputFile file = fileBuilder.build();
componentStore.put("foo", file);
return file;
}
private Duplication[] readDuplications(int expected) {
return readDuplications(batchComponent1, expected);
}
private Duplication[] readDuplications(DefaultInputFile file, int expected) {
assertThat(reader.readComponentDuplications(file.scannerId())).toIterable().hasSize(expected);
Duplication[] duplications = new Duplication[expected];
CloseableIterator<Duplication> dups = reader.readComponentDuplications(file.scannerId());
for (int i = 0; i < expected; i++) {
duplications[i] = dups.next();
}
dups.close();
return duplications;
}
private void assertDuplicate(Duplicate d, int otherFileRef, int rangeStartLine, int rangeEndLine) {
assertThat(d.getOtherFileRef()).isEqualTo(otherFileRef);
assertThat(d.getRange().getStartLine()).isEqualTo(rangeStartLine);
assertThat(d.getRange().getEndLine()).isEqualTo(rangeEndLine);
}
private void assertDuplication(Duplication d, int originStartLine, int originEndLine, int numDuplicates) {
assertThat(d.getOriginPosition().getStartLine()).isEqualTo(originStartLine);
assertThat(d.getOriginPosition().getEndLine()).isEqualTo(originEndLine);
assertThat(d.getDuplicateList()).hasSize(numDuplicates);
}
private void assertDuplication(Duplication d, int originStartLine, int originEndLine, @Nullable Integer otherFileRef, int rangeStartLine, int rangeEndLine) {
assertThat(d.getOriginPosition().getStartLine()).isEqualTo(originStartLine);
assertThat(d.getOriginPosition().getEndLine()).isEqualTo(originEndLine);
assertThat(d.getDuplicateList()).hasSize(1);
if (otherFileRef != null) {
assertThat(d.getDuplicate(0).getOtherFileRef()).isEqualTo(otherFileRef);
} else {
assertThat(d.getDuplicate(0).getOtherFileRef()).isZero();
}
assertThat(d.getDuplicate(0).getRange().getStartLine()).isEqualTo(rangeStartLine);
assertThat(d.getDuplicate(0).getRange().getEndLine()).isEqualTo(rangeEndLine);
}
private CloneGroup newCloneGroup(ClonePart... parts) {
return CloneGroup.builder().setLength(0).setOrigin(parts[0]).setParts(Arrays.asList(parts)).build();
}
}
| 12,241 | 41.804196 | 159 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/CpdSettingsTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.cpd;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CpdSettingsTest {
private CpdSettings cpdSettings;
private Configuration configuration;
@Before
public void setUp() {
configuration = mock(Configuration.class);
cpdSettings = new CpdSettings(configuration);
}
@Test
public void defaultMinimumTokens() {
when(configuration.getInt(anyString())).thenReturn(Optional.empty());
assertThat(cpdSettings.getMinimumTokens("java")).isEqualTo(100);
}
@Test
public void minimumTokensByLanguage() {
when(configuration.getInt("sonar.cpd.java.minimumTokens")).thenReturn(Optional.of(42));
when(configuration.getInt("sonar.cpd.php.minimumTokens")).thenReturn(Optional.of(33));
assertThat(cpdSettings.getMinimumTokens("java")).isEqualTo(42);
assertThat(cpdSettings.getMinimumTokens("php")).isEqualTo(33);
}
}
| 1,999 | 34.087719 | 91 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/DuplicationPredicatesTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.cpd;
import java.util.function.Predicate;
import org.junit.Test;
import org.sonar.duplications.index.CloneGroup;
import static org.assertj.core.api.Assertions.assertThat;
public class DuplicationPredicatesTest {
@Test
public void testNumberOfUnitsNotLessThan() {
Predicate<CloneGroup> predicate = DuplicationPredicates.numberOfUnitsNotLessThan(5);
assertThat(predicate.test(CloneGroup.builder().setLengthInUnits(6).build())).isTrue();
assertThat(predicate.test(CloneGroup.builder().setLengthInUnits(5).build())).isTrue();
assertThat(predicate.test(CloneGroup.builder().setLengthInUnits(4).build())).isFalse();
}
}
| 1,510 | 37.74359 | 91 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/JavaCpdBlockIndexerSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.cpd;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.duplications.block.Block;
import org.sonar.scanner.cpd.index.SonarCpdBlockIndex;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
public class JavaCpdBlockIndexerSensorTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private SensorContextTester context;
@Mock
private SonarCpdBlockIndex index;
private ArgumentCaptor<List<Block>> blockCaptor = ArgumentCaptor.forClass(List.class);
private DefaultInputFile file;
@Before
public void prepare() throws IOException {
MockitoAnnotations.initMocks(this);
File baseDir = temp.newFolder();
context = SensorContextTester.create(baseDir);
file = new TestInputFileBuilder("foo", "src/ManyStatements.java")
.setModuleBaseDir(baseDir.toPath())
.setCharset(StandardCharsets.UTF_8)
.setLanguage("java").build();
context.fileSystem().add(file);
File ioFile = file.file();
FileUtils.copyURLToFile(this.getClass().getResource("ManyStatements.java"), ioFile);
}
@Test
public void testExclusions() {
file.setExcludedForDuplication(true);
new JavaCpdBlockIndexerSensor(index).execute(context);
verifyNoInteractions(index);
}
@Test
public void testJavaIndexing() {
new JavaCpdBlockIndexerSensor(index).execute(context);
verify(index).insert(eq(file), blockCaptor.capture());
List<Block> blockList = blockCaptor.getValue();
assertThat(blockList).hasSize(26);
}
}
| 3,017 | 32.533333 | 88 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/deprecated/test/DefaultTestCaseTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.deprecated.test;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultTestCaseTest {
private final DefaultTestCase testCase = new DefaultTestCase();
@Test
public void getters_after_setters() {
testCase
.setName("name")
.setType("type")
.setDurationInMs(1234L)
.setStatus(DefaultTestCase.Status.FAILURE);
assertThat(testCase.status()).isEqualTo(DefaultTestCase.Status.FAILURE);
assertThat(testCase.name()).isEqualTo("name");
assertThat(testCase.type()).isEqualTo("type");
assertThat(testCase.durationInMs()).isEqualTo(1234L);
}
}
| 1,503 | 33.976744 | 76 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/extension/ScannerCoreExtensionsInstallerTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.extension;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.stream.Stream;
import org.junit.Test;
import org.sonar.api.SonarRuntime;
import org.sonar.api.scanner.ScannerSide;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.server.ServerSide;
import org.sonar.core.extension.CoreExtension;
import org.sonar.core.extension.CoreExtensionRepository;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.core.extension.CoreExtensionsInstaller.noAdditionalSideFilter;
import static org.sonar.core.extension.CoreExtensionsInstaller.noExtensionFilter;
public class ScannerCoreExtensionsInstallerTest {
private final SonarRuntime sonarRuntime = mock(SonarRuntime.class);
private final CoreExtensionRepository coreExtensionRepository = mock(CoreExtensionRepository.class);
private final ScannerCoreExtensionsInstaller underTest = new ScannerCoreExtensionsInstaller(sonarRuntime, coreExtensionRepository);
@Test
public void install_only_adds_ScannerSide_annotated_extension_to_container() {
when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(Stream.of(
new CoreExtension() {
@Override
public String getName() {
return "foo";
}
@Override
public void load(Context context) {
context.addExtensions(CeClass.class, ScannerClass.class, WebServerClass.class,
NoAnnotationClass.class, OtherAnnotationClass.class, MultipleAnnotationClass.class);
}
}));
ListContainer container = new ListContainer();
underTest.install(container, noExtensionFilter(), noAdditionalSideFilter());
assertThat(container.getAddedObjects())
.hasSize(2)
.contains(ScannerClass.class, MultipleAnnotationClass.class);
}
@ComputeEngineSide
public static final class CeClass {
}
@ServerSide
public static final class WebServerClass {
}
@ScannerSide
public static final class ScannerClass {
}
@ServerSide
@ComputeEngineSide
@ScannerSide
public static final class MultipleAnnotationClass {
}
public static final class NoAnnotationClass {
}
@DarkSide
public static final class OtherAnnotationClass {
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DarkSide {
}
}
| 3,481 | 30.369369 | 133 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/ExternalIssueImporterTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.externalissue;
import java.io.File;
import javax.annotation.Nullable;
import org.apache.commons.lang.math.RandomUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.batch.sensor.issue.ExternalIssue;
import org.sonar.api.testfixtures.log.LogTester;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.commons.lang.ObjectUtils.defaultIfNull;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
public class ExternalIssueImporterTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logs = new LogTester();
private DefaultInputFile sourceFile;
private SensorContextTester context;
@Before
public void prepare() throws Exception {
File baseDir = temp.newFolder();
context = SensorContextTester.create(baseDir);
sourceFile = new TestInputFileBuilder("foo", "src/Foo.java")
.setModuleBaseDir(baseDir.toPath())
.initMetadata("the first line\nthe second line")
.setCharset(UTF_8)
.setLanguage("java")
.build();
context.fileSystem().add(sourceFile);
}
@Test
public void import_zero_issues() {
ReportParser.Report report = new ReportParser.Report();
report.issues = new ReportParser.Issue[0];
ExternalIssueImporter underTest = new ExternalIssueImporter(this.context, report);
underTest.execute();
assertThat(context.allExternalIssues()).isEmpty();
assertThat(context.allIssues()).isEmpty();
assertThat(logs.logs(Level.INFO)).contains("Imported 0 issues in 0 files");
}
@Test
public void import_issue_with_minimal_info() {
ReportParser.Report report = new ReportParser.Report();
ReportParser.Issue input = new ReportParser.Issue();
input.engineId = "findbugs";
input.ruleId = "123";
input.severity = "CRITICAL";
input.type = "BUG";
input.primaryLocation = new ReportParser.Location();
input.primaryLocation.filePath = sourceFile.getProjectRelativePath();
input.primaryLocation.message = randomAlphabetic(5);
report.issues = new ReportParser.Issue[] {input};
ExternalIssueImporter underTest = new ExternalIssueImporter(this.context, report);
underTest.execute();
assertThat(context.allExternalIssues()).hasSize(1);
ExternalIssue output = context.allExternalIssues().iterator().next();
assertThat(output.engineId()).isEqualTo(input.engineId);
assertThat(output.ruleId()).isEqualTo(input.ruleId);
assertThat(output.severity()).isEqualTo(Severity.valueOf(input.severity));
assertThat(output.remediationEffort()).isNull();
assertThat(logs.logs(Level.INFO)).contains("Imported 1 issue in 1 file");
}
@Test
public void import_issue_with_complete_primary_location() {
ReportParser.TextRange input = new ReportParser.TextRange();
input.startLine = 1;
input.startColumn = 4;
input.endLine = 2;
input.endColumn = 3;
runOn(newIssue(input));
assertThat(context.allExternalIssues()).hasSize(1);
ExternalIssue output = context.allExternalIssues().iterator().next();
assertSameRange(input, output.primaryLocation().textRange());
}
/**
* If columns are not defined, then issue is assumed to be on the full first line.
* The end line is ignored.
*/
@Test
public void import_issue_with_no_columns() {
ReportParser.TextRange input = new ReportParser.TextRange();
input.startLine = 1;
input.startColumn = null;
input.endLine = 2;
input.endColumn = null;
runOn(newIssue(input));
assertThat(context.allExternalIssues()).hasSize(1);
TextRange got = context.allExternalIssues().iterator().next().primaryLocation().textRange();
assertThat(got.start().line()).isEqualTo(input.startLine);
assertThat(got.start().lineOffset()).isZero();
assertThat(got.end().line()).isEqualTo(input.startLine);
assertThat(got.end().lineOffset()).isEqualTo(sourceFile.selectLine(input.startLine).end().lineOffset());
}
/**
* If end column is not defined, then issue is assumed to be until the last character of the end line.
*/
@Test
public void import_issue_with_start_but_not_end_column() {
ReportParser.TextRange input = new ReportParser.TextRange();
input.startLine = 1;
input.startColumn = 3;
input.endLine = 2;
input.endColumn = null;
runOn(newIssue(input));
assertThat(context.allExternalIssues()).hasSize(1);
TextRange got = context.allExternalIssues().iterator().next().primaryLocation().textRange();
assertThat(got.start().line()).isEqualTo(input.startLine);
assertThat(got.start().lineOffset()).isEqualTo(3);
assertThat(got.end().line()).isEqualTo(input.endLine);
assertThat(got.end().lineOffset()).isEqualTo(sourceFile.selectLine(input.endLine).end().lineOffset());
}
private void assertSameRange(ReportParser.TextRange expected, TextRange got) {
assertThat(got.start().line()).isEqualTo(expected.startLine);
assertThat(got.start().lineOffset()).isEqualTo(defaultIfNull(expected.startColumn, 0));
assertThat(got.end().line()).isEqualTo(expected.endLine);
assertThat(got.end().lineOffset()).isEqualTo(defaultIfNull(expected.endColumn, 0));
}
private void runOn(ReportParser.Issue input) {
ReportParser.Report report = new ReportParser.Report();
report.issues = new ReportParser.Issue[] {input};
ExternalIssueImporter underTest = new ExternalIssueImporter(this.context, report);
underTest.execute();
}
private ReportParser.Issue newIssue(@Nullable ReportParser.TextRange textRange) {
ReportParser.Issue input = new ReportParser.Issue();
input.engineId = randomAlphabetic(5);
input.ruleId = randomAlphabetic(5);
input.severity = "CRITICAL";
input.type = "BUG";
input.effortMinutes = RandomUtils.nextInt();
input.primaryLocation = new ReportParser.Location();
input.primaryLocation.filePath = sourceFile.getProjectRelativePath();
input.primaryLocation.message = randomAlphabetic(5);
input.primaryLocation.textRange = textRange;
return input;
}
}
| 7,350 | 37.689474 | 108 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/ReportParserTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.externalissue;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Test;
import org.sonar.scanner.externalissue.ReportParser.Report;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ReportParserTest {
@Test
public void parse_sample() {
ReportParser parser = new ReportParser(Paths.get("src/test/resources/org/sonar/scanner/externalissue/report.json"));
Report report = parser.parse();
assertThat(report.issues).hasSize(4);
assertThat(report.issues[0].engineId).isEqualTo("eslint");
assertThat(report.issues[0].ruleId).isEqualTo("rule1");
assertThat(report.issues[0].severity).isEqualTo("MAJOR");
assertThat(report.issues[0].effortMinutes).isEqualTo(40);
assertThat(report.issues[0].type).isEqualTo("CODE_SMELL");
assertThat(report.issues[0].primaryLocation.filePath).isEqualTo("file1.js");
assertThat(report.issues[0].primaryLocation.message).isEqualTo("fix the issue here");
assertThat(report.issues[0].primaryLocation.textRange.startColumn).isEqualTo(2);
assertThat(report.issues[0].primaryLocation.textRange.startLine).isOne();
assertThat(report.issues[0].primaryLocation.textRange.endColumn).isEqualTo(4);
assertThat(report.issues[0].primaryLocation.textRange.endLine).isEqualTo(3);
assertThat(report.issues[0].secondaryLocations).isNull();
assertThat(report.issues[3].engineId).isEqualTo("eslint");
assertThat(report.issues[3].ruleId).isEqualTo("rule3");
assertThat(report.issues[3].severity).isEqualTo("MAJOR");
assertThat(report.issues[3].effortMinutes).isNull();
assertThat(report.issues[3].type).isEqualTo("BUG");
assertThat(report.issues[3].secondaryLocations).hasSize(2);
assertThat(report.issues[3].secondaryLocations[0].filePath).isEqualTo("file1.js");
assertThat(report.issues[3].secondaryLocations[0].message).isEqualTo("fix the bug here");
assertThat(report.issues[3].secondaryLocations[0].textRange.startLine).isOne();
assertThat(report.issues[3].secondaryLocations[1].filePath).isEqualTo("file2.js");
assertThat(report.issues[3].secondaryLocations[1].message).isNull();
assertThat(report.issues[3].secondaryLocations[1].textRange.startLine).isEqualTo(2);
}
private Path path(String reportName) {
return Paths.get("src/test/resources/org/sonar/scanner/externalissue/" + reportName);
}
@Test
public void fail_if_report_doesnt_exist() {
ReportParser parser = new ReportParser(Paths.get("unknown.json"));
assertThatThrownBy(() -> parser.parse())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to read external issues report 'unknown.json'");
}
@Test
public void fail_if_report_is_not_valid_json() {
ReportParser parser = new ReportParser(path("report_invalid_json.json"));
assertThatThrownBy(() -> parser.parse())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("invalid JSON syntax");
}
@Test
public void fail_if_primaryLocation_not_set() {
ReportParser parser = new ReportParser(path("report_missing_primaryLocation.json"));
assertThatThrownBy(() -> parser.parse())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("missing mandatory field 'primaryLocation'");
}
@Test
public void fail_if_engineId_not_set() {
ReportParser parser = new ReportParser(path("report_missing_engineId.json"));
assertThatThrownBy(() -> parser.parse())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("missing mandatory field 'engineId'");
}
@Test
public void fail_if_ruleId_not_set() {
ReportParser parser = new ReportParser(path("report_missing_ruleId.json"));
assertThatThrownBy(() -> parser.parse())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("missing mandatory field 'ruleId'");
}
@Test
public void fail_if_severity_not_set() {
ReportParser parser = new ReportParser(path("report_missing_severity.json"));
assertThatThrownBy(() -> parser.parse())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("missing mandatory field 'severity'");
}
@Test
public void fail_if_type_not_set() {
ReportParser parser = new ReportParser(path("report_missing_type.json"));
assertThatThrownBy(() -> parser.parse())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("missing mandatory field 'type'");
}
@Test
public void fail_if_filePath_not_set_in_primaryLocation() {
ReportParser parser = new ReportParser(path("report_missing_filePath.json"));
assertThatThrownBy(() -> parser.parse())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("missing mandatory field 'filePath'");
}
@Test
public void fail_if_message_not_set_in_primaryLocation() {
ReportParser parser = new ReportParser(path("report_missing_message.json"));
assertThatThrownBy(() -> parser.parse())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("missing mandatory field 'message'");
}
}
| 6,038 | 38.993377 | 120 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/sarif/DefaultSarif210ImporterTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.externalissue.sarif;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.event.Level;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.sarif.Run;
import org.sonar.core.sarif.Sarif210;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DefaultSarif210ImporterTest extends TestCase {
@Mock
private RunMapper runMapper;
@Rule
public LogTester logTester = new LogTester();
@InjectMocks
DefaultSarif210Importer sarif210Importer;
@Test
public void importSarif_shouldDelegateRunMapping_toRunMapper() {
Sarif210 sarif210 = mock(Sarif210.class);
Run run1 = mock(Run.class);
Run run2 = mock(Run.class);
when(sarif210.getRuns()).thenReturn(Set.of(run1, run2));
NewExternalIssue issue1run1 = mock(NewExternalIssue.class);
NewExternalIssue issue2run1 = mock(NewExternalIssue.class);
NewExternalIssue issue1run2 = mock(NewExternalIssue.class);
when(runMapper.mapRun(run1)).thenReturn(List.of(issue1run1, issue2run1));
when(runMapper.mapRun(run2)).thenReturn(List.of(issue1run2));
SarifImportResults sarifImportResults = sarif210Importer.importSarif(sarif210);
assertThat(sarifImportResults.getSuccessFullyImportedIssues()).isEqualTo(3);
assertThat(sarifImportResults.getSuccessFullyImportedRuns()).isEqualTo(2);
assertThat(sarifImportResults.getFailedRuns()).isZero();
verify(issue1run1).save();
verify(issue2run1).save();
verify(issue1run2).save();
}
@Test
public void importSarif_whenExceptionThrownByRunMapper_shouldLogAndContinueProcessing() {
Sarif210 sarif210 = mock(Sarif210.class);
Run run1 = mock(Run.class);
Run run2 = mock(Run.class);
when(sarif210.getRuns()).thenReturn(Set.of(run1, run2));
Exception testException = new RuntimeException("test");
when(runMapper.mapRun(run1)).thenThrow(testException);
NewExternalIssue issue1run2 = mock(NewExternalIssue.class);
when(runMapper.mapRun(run2)).thenReturn(List.of(issue1run2));
SarifImportResults sarifImportResults = sarif210Importer.importSarif(sarif210);
assertThat(sarifImportResults.getSuccessFullyImportedIssues()).isOne();
assertThat(sarifImportResults.getSuccessFullyImportedRuns()).isOne();
assertThat(sarifImportResults.getFailedRuns()).isOne();
assertThat(logTester.logs(Level.WARN)).containsOnly("Failed to import a sarif run, error: " + testException.getMessage());
verify(issue1run2).save();
}
@Test
public void importSarif_whenGetRunsReturnNull_shouldFailWithProperMessage() {
Sarif210 sarif210 = mock(Sarif210.class);
when(sarif210.getRuns()).thenReturn(null);
assertThatNullPointerException()
.isThrownBy(() -> sarif210Importer.importSarif(sarif210))
.withMessage("The runs section of the Sarif report is null");
verifyNoInteractions(runMapper);
}
}
| 4,294 | 36.025862 | 126 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/sarif/LocationMapperTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.externalissue.sarif;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.scanner.fs.InputProject;
import org.sonar.core.sarif.Location;
import org.sonar.core.sarif.Result;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class LocationMapperTest {
private static final String TEST_MESSAGE = "test message";
private static final String URI_TEST = "URI_TEST";
private static final String EXPECTED_MESSAGE_URI_MISSING = "The field location.physicalLocation.artifactLocation.uri is not set.";
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private SensorContext sensorContext;
@Mock
private RegionMapper regionMapper;
@InjectMocks
private LocationMapper locationMapper;
@Mock
private NewIssueLocation newIssueLocation;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Result result;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Location location;
@Mock
private InputFile inputFile;
@Before
public void setup() {
when(newIssueLocation.message(any())).thenReturn(newIssueLocation);
when(newIssueLocation.on(any())).thenReturn(newIssueLocation);
when(newIssueLocation.at(any())).thenReturn(newIssueLocation);
when(sensorContext.project()).thenReturn(mock(InputProject.class));
when(result.getMessage().getText()).thenReturn(TEST_MESSAGE);
when(location.getPhysicalLocation().getArtifactLocation().getUri()).thenReturn(URI_TEST);
when(sensorContext.fileSystem().inputFile(any(FilePredicate.class))).thenReturn(inputFile);
}
@Test
public void isPredicate_whenDifferentFile_returnsFalse() {
Path path = Paths.get("file");
InputFile inputFile = mock(InputFile.class);
when((inputFile.path())).thenReturn(Paths.get("file2"));
LocationMapper.IsPredicate isPredicate = new LocationMapper.IsPredicate(path);
assertThat(isPredicate.apply(inputFile)).isFalse();
}
@Test
public void isPredicate_whenSameFile_returnsTrue() {
Path path = Paths.get("file");
InputFile inputFile = mock(InputFile.class);
when((inputFile.path())).thenReturn(path);
LocationMapper.IsPredicate isPredicate = new LocationMapper.IsPredicate(path);
assertThat(isPredicate.apply(inputFile)).isTrue();
}
@Test
public void fillIssueInFileLocation_whenFileNotFound_returnsNull() {
when(sensorContext.fileSystem().inputFile(any())).thenReturn(null);
NewIssueLocation actualIssueLocation = locationMapper.fillIssueInFileLocation(result, newIssueLocation, location);
assertThat(actualIssueLocation).isNull();
}
@Test
public void fillIssueInFileLocation_whenMapRegionReturnsNull_onlyFillsSimpleFields() {
when(regionMapper.mapRegion(location.getPhysicalLocation().getRegion(), inputFile))
.thenReturn(Optional.empty());
NewIssueLocation actualIssueLocation = locationMapper.fillIssueInFileLocation(result, newIssueLocation, location);
assertThat(actualIssueLocation).isSameAs(newIssueLocation);
verify(newIssueLocation).message(TEST_MESSAGE);
verify(newIssueLocation).on(inputFile);
verifyNoMoreInteractions(newIssueLocation);
}
@Test
public void fillIssueInFileLocation_whenMapRegionReturnsRegion_callsAt() {
TextRange textRange = mock(TextRange.class);
when(regionMapper.mapRegion(location.getPhysicalLocation().getRegion(), inputFile))
.thenReturn(Optional.of(textRange));
NewIssueLocation actualIssueLocation = locationMapper.fillIssueInFileLocation(result, newIssueLocation, location);
assertThat(actualIssueLocation).isSameAs(newIssueLocation);
verify(newIssueLocation).message(TEST_MESSAGE);
verify(newIssueLocation).on(inputFile);
verify(newIssueLocation).at(textRange);
verifyNoMoreInteractions(newIssueLocation);
}
@Test
public void fillIssueInFileLocation_ifNullUri_throws() {
when(location.getPhysicalLocation().getArtifactLocation().getUri()).thenReturn(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> locationMapper.fillIssueInFileLocation(result, newIssueLocation, location))
.withMessage(EXPECTED_MESSAGE_URI_MISSING);
}
@Test
public void fillIssueInFileLocation_ifNullArtifactLocation_throws() {
when(location.getPhysicalLocation().getArtifactLocation()).thenReturn(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> locationMapper.fillIssueInFileLocation(result, newIssueLocation, location))
.withMessage(EXPECTED_MESSAGE_URI_MISSING);
}
@Test
public void fillIssueInFileLocation_ifNullPhysicalLocation_throws() {
when(location.getPhysicalLocation().getArtifactLocation()).thenReturn(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> locationMapper.fillIssueInFileLocation(result, newIssueLocation, location))
.withMessage(EXPECTED_MESSAGE_URI_MISSING);
}
}
| 6,519 | 36.906977 | 132 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/sarif/RegionMapperTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.externalissue.sarif;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.DefaultIndexedFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.Metadata;
import org.sonar.core.sarif.Region;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import static org.assertj.core.api.Fail.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(DataProviderRunner.class)
public class RegionMapperTest {
private static final int LINE_END_OFFSET = 10;
private static final DefaultInputFile INPUT_FILE = new DefaultInputFile(new DefaultIndexedFile("ABCDE", Paths.get("module"), "relative/path", null),
f -> f.setMetadata(generateMetadata()), f -> {
});
private static Metadata generateMetadata() {
Metadata metadata = mock(Metadata.class);
when(metadata.lines()).thenReturn(100);
when(metadata.originalLineStartOffsets()).thenReturn(IntStream.range(0, 100).toArray());
when(metadata.originalLineEndOffsets()).thenReturn(IntStream.range(0, 100).map(i -> i + LINE_END_OFFSET).toArray());
return metadata;
}
@Mock
private Region region;
@InjectMocks
private RegionMapper regionMapper;
@Before
public void setup() {
MockitoAnnotations.openMocks(this);
}
@Test
public void mapRegion_whenNullRegion_returnsEmpty() {
assertThat(regionMapper.mapRegion(null, INPUT_FILE)).isEmpty();
}
@Test
public void mapRegion_whenStartLineIsNull_shouldThrow() {
when(region.getStartLine()).thenReturn(null);
assertThatNullPointerException()
.isThrownBy(() -> regionMapper.mapRegion(region, INPUT_FILE))
.withMessage("No start line defined for the region.");
}
@Test
@UseDataProvider("index")
public void mapRegion_whenColumnsDefined_convert1BasedIndexTo0BasedIndex(int startColumn, int endColumn, int startOffsetExpected, int endOffsetExpected) {
Region fullRegion = mockRegion(startColumn, endColumn, 3, 4);
TextRange textRange = regionMapper.mapRegion(fullRegion, INPUT_FILE).orElseGet(() -> fail("No TextRange"));
assertThat(textRange.start().lineOffset()).isEqualTo(startOffsetExpected);
assertThat(textRange.end().lineOffset()).isEqualTo(endOffsetExpected);
}
@DataProvider
public static Object[][] index() {
return new Object[][] {
{1, 3, 0, 2},
{5, 8, 4, 7}
};
}
@Test
public void mapRegion_whenAllCoordinatesDefined() {
Region fullRegion = mockRegion(1, 2, 3, 4);
Optional<TextRange> optTextRange = regionMapper.mapRegion(fullRegion, INPUT_FILE);
assertThat(optTextRange).isPresent();
TextRange textRange = optTextRange.get();
assertThat(textRange.start().line()).isEqualTo(fullRegion.getStartLine());
assertThat(textRange.start().lineOffset()).isZero();
assertThat(textRange.end().line()).isEqualTo(fullRegion.getEndLine());
assertThat(textRange.end().lineOffset()).isEqualTo(1);
}
@Test
public void mapRegion_whenStartEndLinesDefined() {
Region fullRegion = mockRegion(null, null, 3, 8);
Optional<TextRange> optTextRange = regionMapper.mapRegion(fullRegion, INPUT_FILE);
assertThat(optTextRange).isPresent();
TextRange textRange = optTextRange.get();
assertThat(textRange.start().line()).isEqualTo(fullRegion.getStartLine());
assertThat(textRange.start().lineOffset()).isZero();
assertThat(textRange.end().line()).isEqualTo(fullRegion.getEndLine());
assertThat(textRange.end().lineOffset()).isEqualTo(LINE_END_OFFSET);
}
@Test
public void mapRegion_whenStartEndLinesDefinedAndStartColumn() {
Region fullRegion = mockRegion(8, null, 3, 8);
Optional<TextRange> optTextRange = regionMapper.mapRegion(fullRegion, INPUT_FILE);
assertThat(optTextRange).isPresent();
TextRange textRange = optTextRange.get();
assertThat(textRange.start().line()).isEqualTo(fullRegion.getStartLine());
assertThat(textRange.start().lineOffset()).isEqualTo(7);
assertThat(textRange.end().line()).isEqualTo(fullRegion.getEndLine());
assertThat(textRange.end().lineOffset()).isEqualTo(LINE_END_OFFSET);
}
@Test
public void mapRegion_whenStartEndLinesDefinedAndEndColumn() {
Region fullRegion = mockRegion(null, 8, 3, 8);
Optional<TextRange> optTextRange = regionMapper.mapRegion(fullRegion, INPUT_FILE);
assertThat(optTextRange).isPresent();
TextRange textRange = optTextRange.get();
assertThat(textRange.start().line()).isEqualTo(fullRegion.getStartLine());
assertThat(textRange.start().lineOffset()).isZero();
assertThat(textRange.end().line()).isEqualTo(fullRegion.getEndLine());
assertThat(textRange.end().lineOffset()).isEqualTo(7);
}
@Test
public void mapRegion_whenRangeIsEmpty_shouldSelectWholeLine() {
Region fullRegion = mockRegion(8, 8, 3, 3);
Optional<TextRange> optTextRange = regionMapper.mapRegion(fullRegion, INPUT_FILE);
assertThat(optTextRange).isPresent();
TextRange textRange = optTextRange.get();
assertThat(textRange.start().line()).isEqualTo(fullRegion.getStartLine());
assertThat(textRange.start().lineOffset()).isZero();
assertThat(textRange.end().line()).isEqualTo(fullRegion.getEndLine());
assertThat(textRange.end().lineOffset()).isEqualTo(LINE_END_OFFSET);
}
private static Region mockRegion(@Nullable Integer startColumn, @Nullable Integer endColumn, @Nullable Integer startLine, @Nullable Integer endLine) {
Region region = mock(Region.class);
when(region.getStartColumn()).thenReturn(startColumn);
when(region.getEndColumn()).thenReturn(endColumn);
when(region.getStartLine()).thenReturn(startLine);
when(region.getEndLine()).thenReturn(endLine);
return region;
}
}
| 7,180 | 37.607527 | 156 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/sarif/ResultMapperTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.externalissue.sarif;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.rules.RuleType;
import org.sonar.core.sarif.Location;
import org.sonar.core.sarif.Result;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.scanner.externalissue.sarif.ResultMapper.DEFAULT_SEVERITY;
@RunWith(DataProviderRunner.class)
public class ResultMapperTest {
private static final String WARNING = "warning";
private static final String ERROR = "error";
private static final String RULE_ID = "test_rules_id";
private static final String DRIVER_NAME = "driverName";
@Mock
private LocationMapper locationMapper;
@Mock
private SensorContext sensorContext;
@Mock
private NewExternalIssue newExternalIssue;
@Mock
private NewIssueLocation newExternalIssueLocation;
@Mock
private Result result;
@InjectMocks
ResultMapper resultMapper;
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
when(result.getRuleId()).thenReturn(RULE_ID);
when(sensorContext.newExternalIssue()).thenReturn(newExternalIssue);
when(locationMapper.fillIssueInFileLocation(any(), any(), any())).thenReturn(newExternalIssueLocation);
when(locationMapper.fillIssueInProjectLocation(any(), any())).thenReturn(newExternalIssueLocation);
when(newExternalIssue.newLocation()).thenReturn(newExternalIssueLocation);
}
@Test
public void mapResult_mapsSimpleFieldsCorrectly() {
NewExternalIssue newExternalIssue = resultMapper.mapResult(DRIVER_NAME, WARNING, result);
verify(newExternalIssue).type(RuleType.VULNERABILITY);
verify(newExternalIssue).engineId(DRIVER_NAME);
verify(newExternalIssue).severity(DEFAULT_SEVERITY);
verify(newExternalIssue).ruleId(RULE_ID);
}
@Test
public void mapResult_ifRuleIdMissing_fails() {
when(result.getRuleId()).thenReturn(null);
assertThatNullPointerException()
.isThrownBy(() -> resultMapper.mapResult(DRIVER_NAME, WARNING, result))
.withMessage("No ruleId found for issue thrown by driver driverName");
}
@Test
public void mapResult_whenLocationExists_createsFileLocation() {
Location location = mock(Location.class);
when(result.getLocations()).thenReturn(Set.of(location));
NewExternalIssue newExternalIssue = resultMapper.mapResult(DRIVER_NAME, WARNING, result);
verify(locationMapper).fillIssueInFileLocation(result, newExternalIssueLocation, location);
verifyNoMoreInteractions(locationMapper);
verify(newExternalIssue).at(newExternalIssueLocation);
verify(newExternalIssue, never()).addLocation(any());
verify(newExternalIssue, never()).addFlow(any());
}
@Test
public void mapResult_whenLocationExistsButLocationMapperReturnsNull_createsProjectLocation() {
Location location = mock(Location.class);
when(result.getLocations()).thenReturn(Set.of(location));
when(locationMapper.fillIssueInFileLocation(any(), any(), any())).thenReturn(null);
NewExternalIssue newExternalIssue = resultMapper.mapResult(DRIVER_NAME, WARNING, result);
verify(locationMapper).fillIssueInProjectLocation(result, newExternalIssueLocation);
verify(newExternalIssue).at(newExternalIssueLocation);
verify(newExternalIssue, never()).addLocation(any());
verify(newExternalIssue, never()).addFlow(any());
}
@Test
public void mapResult_whenLocationsIsEmpty_createsProjectLocation() {
NewExternalIssue newExternalIssue = resultMapper.mapResult(DRIVER_NAME, WARNING, result);
verify(locationMapper).fillIssueInProjectLocation(result, newExternalIssueLocation);
verifyNoMoreInteractions(locationMapper);
verify(newExternalIssue).at(newExternalIssueLocation);
verify(newExternalIssue, never()).addLocation(any());
verify(newExternalIssue, never()).addFlow(any());
}
@Test
public void mapResult_whenLocationsIsNull_createsProjectLocation() {
when(result.getLocations()).thenReturn(null);
NewExternalIssue newExternalIssue = resultMapper.mapResult(DRIVER_NAME, WARNING, result);
verify(locationMapper).fillIssueInProjectLocation(result, newExternalIssueLocation);
verifyNoMoreInteractions(locationMapper);
verify(newExternalIssue).at(newExternalIssueLocation);
verify(newExternalIssue, never()).addLocation(any());
verify(newExternalIssue, never()).addFlow(any());
}
@Test
public void mapResult_mapsErrorLevel_toCriticalSeverity() {
NewExternalIssue newExternalIssue = resultMapper.mapResult(DRIVER_NAME, ERROR, result);
verify(newExternalIssue).severity(Severity.CRITICAL);
}
@DataProvider
public static Object[][] rule_severity_to_sonarqube_severity_mapping() {
return new Object[][] {
{"error", Severity.CRITICAL},
{"warning", Severity.MAJOR},
{"note", Severity.MINOR},
{"none", Severity.INFO},
{"anything else", DEFAULT_SEVERITY},
{null, DEFAULT_SEVERITY},
};
}
@Test
@UseDataProvider("rule_severity_to_sonarqube_severity_mapping")
public void mapResult_mapsCorrectlyLevelToSeverity(String ruleSeverity, Severity sonarQubeSeverity) {
NewExternalIssue newExternalIssue = resultMapper.mapResult(DRIVER_NAME, ruleSeverity, result);
verify(newExternalIssue).severity(sonarQubeSeverity);
}
}
| 6,956 | 37.65 | 107 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/sarif/RulesSeverityDetectorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.externalissue.sarif;
import java.util.Map;
import java.util.Set;
import org.assertj.core.api.Assertions;
import org.assertj.core.groups.Tuple;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.core.sarif.DefaultConfiguration;
import org.sonar.core.sarif.Driver;
import org.sonar.core.sarif.Extension;
import org.sonar.core.sarif.Result;
import org.sonar.core.sarif.Rule;
import org.sonar.core.sarif.Run;
import org.sonar.core.sarif.Tool;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.scanner.externalissue.sarif.ResultMapper.DEFAULT_SEVERITY;
import static org.sonar.scanner.externalissue.sarif.RulesSeverityDetector.UNSUPPORTED_RULE_SEVERITIES_WARNING;
public class RulesSeverityDetectorTest {
private static final String DRIVER_NAME = "Test";
private static final String WARNING = "warning";
private static final String RULE_ID = "RULE_ID";
@org.junit.Rule
public LogTester logTester = new LogTester().setLevel(LoggerLevel.TRACE);
private final Run run = mock(Run.class);
private final Rule rule = mock(Rule.class);
private final Tool tool = mock(Tool.class);
private final Result result = mock(Result.class);
private final Driver driver = mock(Driver.class);
private final Extension extension = mock(Extension.class);
private final DefaultConfiguration defaultConfiguration = mock(DefaultConfiguration.class);
@Test
public void detectRulesSeverities_detectsCorrectlyResultDefinedRuleSeverities() {
Run run = mockResultDefinedRuleSeverities();
Map<String, String> rulesSeveritiesByRuleId = RulesSeverityDetector.detectRulesSeverities(run, DRIVER_NAME);
assertNoLogs();
assertDetectedRuleSeverities(rulesSeveritiesByRuleId, tuple(RULE_ID, WARNING));
}
@Test
public void detectRulesSeverities_detectsCorrectlyDriverDefinedRuleSeverities() {
Run run = mockDriverDefinedRuleSeverities();
Map<String, String> rulesSeveritiesByRuleId = RulesSeverityDetector.detectRulesSeverities(run, DRIVER_NAME);
assertNoLogs();
assertDetectedRuleSeverities(rulesSeveritiesByRuleId, tuple(RULE_ID, WARNING));
}
@Test
public void detectRulesSeverities_detectsCorrectlyExtensionsDefinedRuleSeverities() {
Run run = mockExtensionsDefinedRuleSeverities();
Map<String, String> rulesSeveritiesByRuleId = RulesSeverityDetector.detectRulesSeverities(run, DRIVER_NAME);
assertNoLogs();
assertDetectedRuleSeverities(rulesSeveritiesByRuleId, tuple(RULE_ID, WARNING));
}
@Test
public void detectRulesSeverities_returnsEmptyMapAndLogsWarning_whenUnableToDetectSeverities() {
Run run = mockUnsupportedRuleSeveritiesDefinition();
Map<String, String> rulesSeveritiesByRuleId = RulesSeverityDetector.detectRulesSeverities(run, DRIVER_NAME);
assertWarningLog(DRIVER_NAME, DEFAULT_SEVERITY);
assertDetectedRuleSeverities(rulesSeveritiesByRuleId);
}
private Run mockResultDefinedRuleSeverities() {
when(run.getResults()).thenReturn(Set.of(result));
when(result.getLevel()).thenReturn(WARNING);
when(result.getRuleId()).thenReturn(RULE_ID);
return run;
}
private Run mockDriverDefinedRuleSeverities() {
when(run.getTool()).thenReturn(tool);
when(tool.getDriver()).thenReturn(driver);
when(driver.getRules()).thenReturn(Set.of(rule));
when(rule.getId()).thenReturn(RULE_ID);
when(rule.getDefaultConfiguration()).thenReturn(defaultConfiguration);
when(defaultConfiguration.getLevel()).thenReturn(WARNING);
return run;
}
private Run mockExtensionsDefinedRuleSeverities() {
when(run.getTool()).thenReturn(tool);
when(tool.getDriver()).thenReturn(driver);
when(driver.getRules()).thenReturn(Set.of());
when(tool.getExtensions()).thenReturn(Set.of(extension));
when(extension.getRules()).thenReturn(Set.of(rule));
when(rule.getId()).thenReturn(RULE_ID);
when(rule.getDefaultConfiguration()).thenReturn(defaultConfiguration);
when(defaultConfiguration.getLevel()).thenReturn(WARNING);
return run;
}
private Run mockUnsupportedRuleSeveritiesDefinition() {
when(run.getTool()).thenReturn(tool);
when(tool.getDriver()).thenReturn(driver);
when(driver.getRules()).thenReturn(Set.of());
when(tool.getExtensions()).thenReturn(Set.of(extension));
when(extension.getRules()).thenReturn(Set.of());
return run;
}
private void assertNoLogs() {
assertThat(logTester.logs()).isEmpty();
}
private static void assertDetectedRuleSeverities(Map<String, String> severities, Tuple... expectedSeverities) {
Assertions.assertThat(severities.entrySet())
.extracting(Map.Entry::getKey, Map.Entry::getValue)
.containsExactly(expectedSeverities);
}
private void assertWarningLog(String driverName, Severity defaultSeverity) {
assertThat(logTester.logs()).hasSize(1);
assertThat(logTester.logs(Level.WARN))
.containsOnly(format(UNSUPPORTED_RULE_SEVERITIES_WARNING, driverName, defaultSeverity));
}
}
| 6,180 | 37.154321 | 113 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/sarif/RunMapperTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.externalissue.sarif;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.event.Level;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.sarif.Result;
import org.sonar.core.sarif.Run;
import static java.util.Collections.emptySet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class RunMapperTest {
private static final String WARNING = "warning";
private static final String TEST_DRIVER = "Test driver";
public static final String RULE_ID = "ruleId";
@Mock
private ResultMapper resultMapper;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Run run;
@Rule
public LogTester logTester = new LogTester();
@InjectMocks
private RunMapper runMapper;
@Test
public void mapRun_delegatesToMapResult() {
when(run.getTool().getDriver().getName()).thenReturn(TEST_DRIVER);
Result result1 = mock(Result.class);
Result result2 = mock(Result.class);
when(run.getResults()).thenReturn(Set.of(result1, result2));
NewExternalIssue externalIssue1 = mockMappedResult(result1);
NewExternalIssue externalIssue2 = mockMappedResult(result2);
try (MockedStatic<RulesSeverityDetector> detector = mockStatic(RulesSeverityDetector.class)) {
detector.when(() -> RulesSeverityDetector.detectRulesSeverities(run, TEST_DRIVER)).thenReturn(Map.of(RULE_ID, WARNING));
List<NewExternalIssue> newExternalIssues = runMapper.mapRun(run);
assertThat(newExternalIssues).containsOnly(externalIssue1, externalIssue2);
assertThat(logTester.logs()).isEmpty();
}
}
@Test
public void mapRun_ifRunIsEmpty_returnsEmptyList() {
when(run.getResults()).thenReturn(emptySet());
List<NewExternalIssue> newExternalIssues = runMapper.mapRun(run);
assertThat(newExternalIssues).isEmpty();
}
@Test
public void mapRun_ifExceptionThrownByResultMapper_logsThemAndContinueProcessing() {
when(run.getTool().getDriver().getName()).thenReturn(TEST_DRIVER);
Result result1 = mock(Result.class);
Result result2 = mock(Result.class);
when(run.getResults()).thenReturn(Set.of(result1, result2));
NewExternalIssue externalIssue2 = mockMappedResult(result2);
when(result1.getRuleId()).thenReturn(RULE_ID);
when(resultMapper.mapResult(TEST_DRIVER, WARNING, result1)).thenThrow(new IllegalArgumentException("test"));
try (MockedStatic<RulesSeverityDetector> detector = mockStatic(RulesSeverityDetector.class)) {
detector.when(() -> RulesSeverityDetector.detectRulesSeverities(run, TEST_DRIVER)).thenReturn(Map.of(RULE_ID, WARNING));
List<NewExternalIssue> newExternalIssues = runMapper.mapRun(run);
assertThat(newExternalIssues)
.containsExactly(externalIssue2);
assertThat(logTester.logs(Level.WARN)).containsOnly("Failed to import an issue raised by tool Test driver, error: test");
}
}
@Test
public void mapRun_failsIfToolNotSet() {
when(run.getTool()).thenReturn(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> runMapper.mapRun(run))
.withMessage("The run does not have a tool driver name defined.");
}
@Test
public void mapRun_failsIfDriverNotSet() {
when(run.getTool().getDriver()).thenReturn(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> runMapper.mapRun(run))
.withMessage("The run does not have a tool driver name defined.");
}
@Test
public void mapRun_failsIfDriverNameIsNotSet() {
when(run.getTool().getDriver().getName()).thenReturn(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> runMapper.mapRun(run))
.withMessage("The run does not have a tool driver name defined.");
}
private NewExternalIssue mockMappedResult(Result result) {
NewExternalIssue externalIssue = mock(NewExternalIssue.class);
when(result.getRuleId()).thenReturn(RULE_ID);
when(resultMapper.mapResult(TEST_DRIVER, WARNING, result)).thenReturn(externalIssue);
return externalIssue;
}
}
| 5,422 | 35.641892 | 127 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/sarif/SarifIssuesImportSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.externalissue.sarif;
import com.google.common.collect.MoreCollectors;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.event.Level;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.testfixtures.log.LogAndArguments;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.core.sarif.Sarif210;
import org.sonar.core.sarif.SarifSerializer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class SarifIssuesImportSensorTest {
private static final String FILE_1 = "path/to/sarif/file.sarif";
private static final String FILE_2 = "path/to/sarif/file2.sarif";
private static final String SARIF_REPORT_PATHS_PARAM = FILE_1 + "," + FILE_2;
@Mock
private SarifSerializer sarifSerializer;
@Mock
private Sarif210Importer sarifImporter;
private MapSettings sensorSettings;
@Before
public void before() {
sensorSettings = new MapSettings();
}
@Rule
public final LogTester logTester = new LogTester();
private final SensorContextTester sensorContext = SensorContextTester.create(Path.of("."));
@Test
public void execute_whenSingleFileIsSpecified_shouldImportResults() throws NoSuchFileException {
sensorSettings.setProperty("sonar.sarifReportPaths", FILE_1);
ReportAndResults reportAndResults = mockSuccessfulReportAndResults(FILE_1);
SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
sensor.execute(sensorContext);
verify(sarifImporter).importSarif(reportAndResults.getSarifReport());
assertThat(logTester.logs(Level.INFO)).hasSize(1);
assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_1, reportAndResults.getSarifImportResults());
}
@Test
public void execute_whenMultipleFilesAreSpecified_shouldImportResults() throws NoSuchFileException {
sensorSettings.setProperty("sonar.sarifReportPaths", SARIF_REPORT_PATHS_PARAM);
ReportAndResults reportAndResults1 = mockSuccessfulReportAndResults(FILE_1);
ReportAndResults reportAndResults2 = mockSuccessfulReportAndResults(FILE_2);
SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
sensor.execute(sensorContext);
verify(sarifImporter).importSarif(reportAndResults1.getSarifReport());
verify(sarifImporter).importSarif(reportAndResults2.getSarifReport());
assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_1, reportAndResults1.getSarifImportResults());
assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_2, reportAndResults2.getSarifImportResults());
}
@Test
public void execute_whenFileContainsOnlySuccessfulRuns_shouldLogCorrectMessage() throws NoSuchFileException {
sensorSettings.setProperty("sonar.sarifReportPaths", FILE_1);
ReportAndResults reportAndResults = mockSuccessfulReportAndResults(FILE_1);
SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
sensor.execute(sensorContext);
assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_1, reportAndResults.getSarifImportResults());
}
@Test
public void execute_whenFileContainsOnlyFailedRuns_shouldLogCorrectMessage() throws NoSuchFileException {
sensorSettings.setProperty("sonar.sarifReportPaths", FILE_1);
ReportAndResults reportAndResults = mockFailedReportAndResults(FILE_1);
SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
sensor.execute(sensorContext);
assertSummaryIsCorrectlyDisplayedForFailedFile(FILE_1, reportAndResults.getSarifImportResults());
}
@Test
public void execute_whenFileContainsFailedAndSuccessfulRuns_shouldLogCorrectMessage() throws NoSuchFileException {
sensorSettings.setProperty("sonar.sarifReportPaths", FILE_1);
ReportAndResults reportAndResults = mockMixedReportAndResults(FILE_1);
SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
sensor.execute(sensorContext);
verify(sarifImporter).importSarif(reportAndResults.getSarifReport());
assertSummaryIsCorrectlyDisplayedForMixedFile(FILE_1, reportAndResults.getSarifImportResults());
}
@Test
public void execute_whenImportFails_shouldSkipReport() throws NoSuchFileException {
sensorSettings.setProperty("sonar.sarifReportPaths", SARIF_REPORT_PATHS_PARAM);
ReportAndResults reportAndResults1 = mockFailedReportAndResults(FILE_1);
ReportAndResults reportAndResults2 = mockSuccessfulReportAndResults(FILE_2);
doThrow(new NullPointerException("import failed")).when(sarifImporter).importSarif(reportAndResults1.getSarifReport());
SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
sensor.execute(sensorContext);
verify(sarifImporter).importSarif(reportAndResults2.getSarifReport());
assertThat(logTester.logs(Level.WARN)).contains("Failed to process SARIF report from file 'path/to/sarif/file.sarif', error: 'import failed'");
assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_2, reportAndResults2.getSarifImportResults());
}
@Test
public void execute_whenDeserializationFails_shouldSkipReport() throws NoSuchFileException {
sensorSettings.setProperty("sonar.sarifReportPaths", SARIF_REPORT_PATHS_PARAM);
failDeserializingReport(FILE_1);
ReportAndResults reportAndResults2 = mockSuccessfulReportAndResults(FILE_2);
SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
sensor.execute(sensorContext);
verify(sarifImporter).importSarif(reportAndResults2.getSarifReport());
assertThat(logTester.logs(Level.WARN)).contains("Failed to process SARIF report from file 'path/to/sarif/file.sarif', error: 'deserialization failed'");
assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_2, reportAndResults2.getSarifImportResults());
}
@Test
public void execute_whenDeserializationThrowsMessageException_shouldRethrow() throws NoSuchFileException {
sensorSettings.setProperty("sonar.sarifReportPaths", FILE_1);
NoSuchFileException e = new NoSuchFileException("non-existent");
failDeserializingReportWithException(FILE_1, e);
SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
assertThatThrownBy(() -> sensor.execute(sensorContext))
.isInstanceOf(MessageException.class)
.hasMessage("SARIF report file not found: non-existent");
}
private void failDeserializingReport(String path) throws NoSuchFileException {
Path reportFilePath = sensorContext.fileSystem().resolvePath(path).toPath();
when(sarifSerializer.deserialize(reportFilePath)).thenThrow(new NullPointerException("deserialization failed"));
}
private void failDeserializingReportWithException(String path, Exception exception) throws NoSuchFileException {
Path reportFilePath = sensorContext.fileSystem().resolvePath(path).toPath();
when(sarifSerializer.deserialize(reportFilePath)).thenThrow(exception);
}
private ReportAndResults mockSuccessfulReportAndResults(String path) throws NoSuchFileException {
Sarif210 report = mockSarifReport(path);
SarifImportResults sarifImportResults = mock(SarifImportResults.class);
when(sarifImportResults.getSuccessFullyImportedIssues()).thenReturn(10);
when(sarifImportResults.getSuccessFullyImportedRuns()).thenReturn(3);
when(sarifImportResults.getFailedRuns()).thenReturn(0);
when(sarifImporter.importSarif(report)).thenReturn(sarifImportResults);
return new ReportAndResults(report, sarifImportResults);
}
private Sarif210 mockSarifReport(String path) throws NoSuchFileException {
Sarif210 report = mock(Sarif210.class);
Path reportFilePath = sensorContext.fileSystem().resolvePath(path).toPath();
when(sarifSerializer.deserialize(reportFilePath)).thenReturn(report);
return report;
}
private ReportAndResults mockFailedReportAndResults(String path) throws NoSuchFileException {
Sarif210 report = mockSarifReport(path);
SarifImportResults sarifImportResults = mock(SarifImportResults.class);
when(sarifImportResults.getSuccessFullyImportedRuns()).thenReturn(0);
when(sarifImportResults.getFailedRuns()).thenReturn(1);
when(sarifImporter.importSarif(report)).thenReturn(sarifImportResults);
return new ReportAndResults(report, sarifImportResults);
}
private ReportAndResults mockMixedReportAndResults(String path) throws NoSuchFileException {
Sarif210 report = mockSarifReport(path);
SarifImportResults sarifImportResults = mock(SarifImportResults.class);
when(sarifImportResults.getSuccessFullyImportedIssues()).thenReturn(10);
when(sarifImportResults.getSuccessFullyImportedRuns()).thenReturn(3);
when(sarifImportResults.getFailedRuns()).thenReturn(1);
when(sarifImporter.importSarif(report)).thenReturn(sarifImportResults);
return new ReportAndResults(report, sarifImportResults);
}
private void assertSummaryIsCorrectlyDisplayedForSuccessfulFile(String filePath, SarifImportResults sarifImportResults) {
verifyLogContainsLine(LoggerLevel.INFO, filePath, "File {}: {} run(s) successfully imported ({} vulnerabilities in total).",
filePath, sarifImportResults.getSuccessFullyImportedRuns(), sarifImportResults.getSuccessFullyImportedIssues());
}
private void assertSummaryIsCorrectlyDisplayedForFailedFile(String filePath, SarifImportResults sarifImportResults) {
verifyLogContainsLine(LoggerLevel.WARN, filePath, "File {}: {} run(s) could not be imported (see warning above).",
filePath, sarifImportResults.getFailedRuns());
}
private void assertSummaryIsCorrectlyDisplayedForMixedFile(String filePath, SarifImportResults sarifImportResults) {
verifyLogContainsLine(LoggerLevel.WARN, filePath,
"File {}: {} run(s) could not be imported (see warning above) and {} run(s) successfully imported ({} vulnerabilities in total).",
filePath, sarifImportResults.getFailedRuns(), sarifImportResults.getSuccessFullyImportedRuns(), sarifImportResults.getSuccessFullyImportedIssues());
}
private void verifyLogContainsLine(LoggerLevel level, String filePath, String rawMsg, Object... arguments) {
LogAndArguments logAndArguments = findLogEntry(level, filePath);
assertThat(logAndArguments.getRawMsg())
.isEqualTo(rawMsg);
assertThat(logAndArguments.getArgs()).isPresent()
.contains(arguments);
}
private LogAndArguments findLogEntry(LoggerLevel level, String filePath) {
Optional<LogAndArguments> optLogAndArguments = logTester.getLogs(level).stream()
.filter(log -> log.getFormattedMsg().contains(filePath))
.collect(MoreCollectors.toOptional());
assertThat(optLogAndArguments).as("Log entry missing for file %s", filePath).isPresent();
return optLogAndArguments.get();
}
private static class ReportAndResults {
private final Sarif210 sarifReport;
private final SarifImportResults sarifImportResults;
private ReportAndResults(Sarif210 sarifReport, SarifImportResults sarifImportResults) {
this.sarifReport = sarifReport;
this.sarifImportResults = sarifImportResults;
}
private Sarif210 getSarifReport() {
return sarifReport;
}
private SarifImportResults getSarifImportResults() {
return sarifImportResults;
}
}
}
| 13,090 | 44.141379 | 156 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/genericcoverage/GenericCoverageReportParserTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.genericcoverage;
import java.io.File;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.utils.MessageException;
import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
public class GenericCoverageReportParserTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logs = new LogTester();
private DefaultInputFile fileWithBranches;
private DefaultInputFile fileWithoutBranch;
private DefaultInputFile emptyFile;
private SensorContextTester context;
@Before
public void before() {
logs.setLevel(Level.DEBUG);
context = SensorContextTester.create(new File(""));
fileWithBranches = setupFile("src/main/java/com/example/ClassWithBranches.java");
fileWithoutBranch = setupFile("src/main/java/com/example/ClassWithoutBranch.java");
emptyFile = setupFile("src/main/java/com/example/EmptyClass.java");
}
@Test
public void empty_file() throws Exception {
addFileToFs(emptyFile);
GenericCoverageReportParser parser = new GenericCoverageReportParser();
parser.parse(new File(this.getClass().getResource("coverage.xml").toURI()), context);
assertThat(parser.numberOfMatchedFiles()).isOne();
assertThat(parser.numberOfUnknownFiles()).isEqualTo(3);
assertThat(parser.firstUnknownFiles()).hasSize(3);
}
@Test
public void file_without_language_should_be_skipped() throws Exception {
String filePath = "src/main/java/com/example/ClassWithBranches.java";
DefaultInputFile file = new TestInputFileBuilder(context.module().key(), filePath)
.setLanguage(null)
.setType(InputFile.Type.TEST)
.initMetadata("1\n2\n3\n4\n5\n6")
.build();
addFileToFs(file);
GenericCoverageReportParser parser = new GenericCoverageReportParser();
parser.parse(new File(this.getClass().getResource("coverage.xml").toURI()), context);
assertThat(parser.numberOfMatchedFiles()).isZero();
assertThat(parser.numberOfUnknownFiles()).isEqualTo(4);
assertThat(parser.firstUnknownFiles()).hasSize(4);
assertThat(logs.logs())
.contains("Skipping file 'src/main/java/com/example/ClassWithBranches.java' in the generic coverage report because it doesn't have a known language");
}
@Test
public void file_without_branch() throws Exception {
addFileToFs(fileWithoutBranch);
GenericCoverageReportParser parser = new GenericCoverageReportParser();
parser.parse(new File(this.getClass().getResource("coverage.xml").toURI()), context);
assertThat(parser.numberOfMatchedFiles()).isOne();
assertThat(context.lineHits(fileWithoutBranch.key(), 2)).isZero();
assertThat(context.lineHits(fileWithoutBranch.key(), 3)).isOne();
assertThat(context.lineHits(fileWithoutBranch.key(), 4)).isNull();
assertThat(context.lineHits(fileWithoutBranch.key(), 5)).isOne();
assertThat(context.lineHits(fileWithoutBranch.key(), 6)).isZero();
}
@Test
public void file_with_branches() throws Exception {
addFileToFs(fileWithBranches);
GenericCoverageReportParser parser = new GenericCoverageReportParser();
parser.parse(new File(this.getClass().getResource("coverage.xml").toURI()), context);
assertThat(parser.numberOfMatchedFiles()).isOne();
assertThat(context.lineHits(fileWithBranches.key(), 3)).isOne();
assertThat(context.lineHits(fileWithBranches.key(), 4)).isOne();
assertThat(context.conditions(fileWithBranches.key(), 3)).isEqualTo(8);
assertThat(context.conditions(fileWithBranches.key(), 4)).isEqualTo(2);
assertThat(context.coveredConditions(fileWithBranches.key(), 3)).isEqualTo(5);
assertThat(context.coveredConditions(fileWithBranches.key(), 4)).isZero();
}
@Test(expected = MessageException.class)
public void coverage_invalid_root_node_name() throws Exception {
parseCoverageReport("<mycoverage version=\"1\"></mycoverage>");
}
@Test(expected = MessageException.class)
public void coverage_invalid_report_version() throws Exception {
parseCoverageReport("<coverage version=\"2\"></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_no_report_version() throws Exception {
parseCoverageReport("<coverage></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_invalid_file_node_name() throws Exception {
parseCoverageReport("<coverage version=\"1\"><xx></xx></coverage>");
}
@Test(expected = MessageException.class)
public void unitTest_invalid_file_node_name() throws Exception {
parseCoverageReport("<unitTest version=\"1\"><xx></xx></unitTest>");
}
@Test(expected = MessageException.class)
public void coverage_missing_path_attribute() throws Exception {
parseCoverageReport("<coverage version=\"1\"><file></file></coverage>");
}
@Test(expected = MessageException.class)
public void unitTest_missing_path_attribute() throws Exception {
parseCoverageReport("<unitTest version=\"1\"><file></file></unitTest>");
}
@Test(expected = MessageException.class)
public void coverage_invalid_lineToCover_node_name() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\"><xx/></file></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_missing_lineNumber_in_lineToCover() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\"><lineToCover covered=\"true\"/></file></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_lineNumber_in_lineToCover_should_be_a_number() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\"><lineToCover lineNumber=\"x\" covered=\"true\"/></file></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_lineNumber_in_lineToCover_should_be_positive() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\"><lineToCover lineNumber=\"0\" covered=\"true\"/></file></coverage>");
}
@Test
public void coverage_lineNumber_in_lineToCover_can_appear_several_times_for_same_file() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\">"
+ "<lineToCover lineNumber=\"1\" covered=\"true\"/>"
+ "<lineToCover lineNumber=\"1\" covered=\"true\"/></file></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_missing_covered_in_lineToCover() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\"><lineToCover lineNumber=\"3\"/></file></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_covered_in_lineToCover_should_be_a_boolean() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\"><lineToCover lineNumber=\"3\" covered=\"x\"/></file></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_branchesToCover_in_lineToCover_should_be_a_number() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\">"
+ "<lineToCover lineNumber=\"1\" covered=\"true\" branchesToCover=\"x\"/></file></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_branchesToCover_in_lineToCover_should_not_be_negative() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\">"
+ "<lineToCover lineNumber=\"1\" covered=\"true\" branchesToCover=\"-1\"/></file></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_coveredBranches_in_lineToCover_should_be_a_number() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\">"
+ "<lineToCover lineNumber=\"1\" covered=\"true\" branchesToCover=\"2\" coveredBranches=\"x\"/></file></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_coveredBranches_in_lineToCover_should_not_be_negative() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\">"
+ "<lineToCover lineNumber=\"1\" covered=\"true\" branchesToCover=\"2\" coveredBranches=\"-1\"/></file></coverage>");
}
@Test(expected = MessageException.class)
public void coverage_coveredBranches_should_not_be_greater_than_branchesToCover() throws Exception {
addFileToFs(setupFile("file1"));
parseCoverageReport("<coverage version=\"1\"><file path=\"file1\">"
+ "<lineToCover lineNumber=\"1\" covered=\"true\" branchesToCover=\"2\" coveredBranches=\"3\"/></file></coverage>");
}
@Test(expected = MessageException.class)
public void testUnknownFile() {
parseCoverageReportFile("xxx.xml");
}
private void addFileToFs(DefaultInputFile inputFile) {
context.fileSystem().add(inputFile);
}
private void parseCoverageReport(String string) throws Exception {
File report = temp.newFile();
FileUtils.write(report, string, StandardCharsets.UTF_8);
new GenericCoverageReportParser().parse(report, context);
}
private void parseCoverageReportFile(String reportLocation) {
new GenericCoverageReportParser().parse(new File(reportLocation), context);
}
private DefaultInputFile setupFile(String path) {
return new TestInputFileBuilder(context.module().key(), path)
.setLanguage("bla")
.setType(InputFile.Type.MAIN)
.initMetadata("1\n2\n3\n4\n5\n6")
.build();
}
}
| 11,109 | 41.895753 | 156 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/genericcoverage/GenericCoverageSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.genericcoverage;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.utils.System2;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.config.DefaultConfiguration;
import org.sonar.scanner.scan.ProjectConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
public class GenericCoverageSensorTest {
@Rule
public LogTester logTester = new LogTester();
@Test
public void loadAllReportPaths() {
Map<String, String> settings = new HashMap<>();
settings.put(GenericCoverageSensor.REPORT_PATHS_PROPERTY_KEY, "report.xml,report2.xml");
PropertyDefinitions defs = new PropertyDefinitions(System2.INSTANCE, GenericCoverageSensor.properties());
DefaultConfiguration config = new ProjectConfiguration(defs, new Encryption(null), settings);
Set<String> reportPaths = new GenericCoverageSensor(config).loadReportPaths();
assertThat(reportPaths).containsOnly("report.xml", "report2.xml");
}
}
| 2,011 | 36.962264 | 109 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/genericcoverage/GenericTestExecutionReportParserTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.genericcoverage;
import java.io.File;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.utils.MessageException;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.deprecated.test.DefaultTestCase;
import org.sonar.scanner.deprecated.test.DefaultTestPlan;
import org.sonar.scanner.deprecated.test.TestPlanBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class GenericTestExecutionReportParserTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logs = new LogTester();
private TestPlanBuilder testPlanBuilder;
private DefaultInputFile fileWithBranches;
private DefaultInputFile emptyFile;
private SensorContextTester context;
private DefaultTestPlan testPlan;
@Before
public void before() {
logs.setLevel(Level.DEBUG);
context = SensorContextTester.create(new File(""));
fileWithBranches = setupFile("src/main/java/com/example/ClassWithBranches.java");
emptyFile = setupFile("src/main/java/com/example/EmptyClass.java");
testPlanBuilder = mock(TestPlanBuilder.class);
DefaultTestCase testCase = mockMutableTestCase();
testPlan = mockMutableTestPlan(testCase);
when(testPlanBuilder.getTestPlan(any(InputFile.class))).thenReturn(testPlan);
}
@Test
public void file_without_language_should_be_skipped() throws Exception {
String filePath = "src/main/java/com/example/EmptyClass.java";
DefaultInputFile file = new TestInputFileBuilder(context.module().key(), filePath)
.setLanguage(null)
.setType(InputFile.Type.TEST)
.initMetadata("1\n2\n3\n4\n5\n6")
.build();
addFileToFs(file);
GenericTestExecutionReportParser parser = parseReportFile("unittest.xml");
assertThat(parser.numberOfMatchedFiles()).isZero();
assertThat(parser.numberOfUnknownFiles()).isEqualTo(2);
assertThat(parser.firstUnknownFiles()).hasSize(2);
assertThat(logs.logs())
.contains("Skipping file 'src/main/java/com/example/EmptyClass.java' in the generic test execution report because it doesn't have a known language");
}
@Test
public void ut_empty_file() throws Exception {
addFileToFs(emptyFile);
GenericTestExecutionReportParser parser = parseReportFile("unittest.xml");
assertThat(parser.numberOfMatchedFiles()).isOne();
assertThat(parser.numberOfUnknownFiles()).isOne();
assertThat(parser.firstUnknownFiles()).hasSize(1);
}
@Test
public void file_with_unittests() throws Exception {
addFileToFs(fileWithBranches);
GenericTestExecutionReportParser parser = parseReportFile("unittest2.xml");
assertThat(parser.numberOfMatchedFiles()).isOne();
verify(testPlan).addTestCase("test1");
verify(testPlan).addTestCase("test2");
verify(testPlan).addTestCase("test3");
}
@Test(expected = MessageException.class)
public void unittest_invalid_root_node_name() throws Exception {
parseUnitTestReport("<mycoverage version=\"1\"></mycoverage>");
}
@Test(expected = MessageException.class)
public void unittest_invalid_report_version() throws Exception {
parseUnitTestReport("<unitTest version=\"2\"></unitTest>");
}
@Test(expected = MessageException.class)
public void unittest_duration_in_testCase_should_not_be_negative() throws Exception {
addFileToFs(setupFile("file1"));
parseUnitTestReport("<unitTest version=\"1\"><file path=\"file1\">"
+ "<testCase name=\"test1\" duration=\"-5\"/></file></unitTest>");
}
private void addFileToFs(DefaultInputFile inputFile) {
context.fileSystem().add(inputFile);
}
private GenericTestExecutionReportParser parseUnitTestReport(String string) throws Exception {
GenericTestExecutionReportParser parser = new GenericTestExecutionReportParser(testPlanBuilder);
File report = temp.newFile();
FileUtils.write(report, string, StandardCharsets.UTF_8);
parser.parse(report, context);
return parser;
}
private GenericTestExecutionReportParser parseReportFile(String reportLocation) throws Exception {
GenericTestExecutionReportParser parser = new GenericTestExecutionReportParser(testPlanBuilder);
parser.parse(new File(this.getClass().getResource(reportLocation).toURI()), context);
return parser;
}
private DefaultInputFile setupFile(String path) {
return new TestInputFileBuilder(context.module().key(), path)
.setLanguage("bla")
.setType(InputFile.Type.TEST)
.initMetadata("1\n2\n3\n4\n5\n6")
.build();
}
private DefaultTestPlan mockMutableTestPlan(DefaultTestCase testCase) {
DefaultTestPlan testPlan = mock(DefaultTestPlan.class);
when(testPlan.addTestCase(anyString())).thenReturn(testCase);
return testPlan;
}
private DefaultTestCase mockMutableTestCase() {
DefaultTestCase testCase = mock(DefaultTestCase.class);
when(testCase.setDurationInMs(anyLong())).thenReturn(testCase);
when(testCase.setStatus(any(DefaultTestCase.Status.class))).thenReturn(testCase);
when(testCase.setType(anyString())).thenReturn(testCase);
return testCase;
}
}
| 6,639 | 38.058824 | 155 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/genericcoverage/GenericTestExecutionSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.genericcoverage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.utils.System2;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.config.DefaultConfiguration;
import org.sonar.scanner.deprecated.test.TestPlanBuilder;
import org.sonar.scanner.scan.ProjectConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class GenericTestExecutionSensorTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
@Test
public void logWhenDeprecatedPropsAreUsed() throws IOException {
File basedir = temp.newFolder();
File report = new File(basedir, "report.xml");
FileUtils.write(report, "<unitTest version=\"1\"><file path=\"A.java\"><testCase name=\"test1\" duration=\"500\"/></file></unitTest>", StandardCharsets.UTF_8);
SensorContextTester context = SensorContextTester.create(basedir);
Map<String, String> settings = new HashMap<>();
settings.put(GenericTestExecutionSensor.OLD_UNIT_TEST_REPORT_PATHS_PROPERTY_KEY, "report.xml");
PropertyDefinitions defs = new PropertyDefinitions(System2.INSTANCE, GenericTestExecutionSensor.properties());
DefaultConfiguration config = new ProjectConfiguration(defs, new Encryption(null), settings);
new GenericTestExecutionSensor(mock(TestPlanBuilder.class), config).execute(context);
assertThat(logTester.logs(Level.WARN)).contains(
"Using 'unitTest' as root element of the report is deprecated. Please change to 'testExecutions'.",
"Property 'sonar.genericcoverage.unitTestReportPaths' is deprecated. Please use 'sonar.testExecutionReportPaths' instead.");
assertThat(logTester.logs(Level.INFO)).contains(
"Imported test execution data for 0 files",
"Test execution data ignored for 1 unknown files, including:\nA.java");
}
}
| 3,194 | 42.175676 | 163 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/genericcoverage/StaxParserTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.genericcoverage;
import org.codehaus.staxmate.in.SMHierarchicCursor;
import org.junit.Test;
import javax.xml.stream.XMLStreamException;
public class StaxParserTest {
@Test
public void testXMLWithDTD() throws XMLStreamException {
StaxParser parser = new StaxParser(getTestHandler());
parser.parse(getClass().getClassLoader().getResourceAsStream("org/sonar/scanner/genericcoverage/xml-dtd-test.xml"));
}
@Test
public void testXMLWithXSD() throws XMLStreamException {
StaxParser parser = new StaxParser(getTestHandler());
parser.parse(getClass().getClassLoader().getResourceAsStream("org/sonar/scanner/genericcoverage/xml-xsd-test.xml"));
}
private StaxParser.XmlStreamHandler getTestHandler() {
return new StaxParser.XmlStreamHandler() {
public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException {
rootCursor.advance();
while (rootCursor.getNext() != null) {
}
}
};
}
}
| 1,838 | 34.365385 | 120 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DefaultFilterableIssueTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.issue;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.scanner.protocol.Constants.Severity;
import org.sonar.scanner.protocol.output.ScannerReport.Issue;
import org.sonar.scanner.protocol.output.ScannerReport.TextRange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DefaultFilterableIssueTest {
private DefaultFilterableIssue issue;
private DefaultInputProject mockedProject;
private InputComponent component;
private Issue rawIssue;
@Before
public void setUp() {
mockedProject = mock(DefaultInputProject.class);
component = mock(InputComponent.class);
when(component.key()).thenReturn("foo");
}
private Issue createIssue() {
Issue.Builder builder = Issue.newBuilder();
builder.setGap(3.0);
builder.setTextRange(TextRange.newBuilder()
.setStartLine(30)
.setStartOffset(10)
.setEndLine(31)
.setEndOffset(3));
builder.setSeverity(Severity.MAJOR);
return builder.build();
}
private Issue createIssueWithoutFields() {
Issue.Builder builder = Issue.newBuilder();
builder.setSeverity(Severity.MAJOR);
return builder.build();
}
@Test
public void testRoundTrip() {
rawIssue = createIssue();
issue = new DefaultFilterableIssue(mockedProject, rawIssue, component);
when(mockedProject.key()).thenReturn("projectKey");
assertThat(issue.componentKey()).isEqualTo(component.key());
assertThat(issue.line()).isEqualTo(30);
assertThat(issue.textRange().start().line()).isEqualTo(30);
assertThat(issue.textRange().start().lineOffset()).isEqualTo(10);
assertThat(issue.textRange().end().line()).isEqualTo(31);
assertThat(issue.textRange().end().lineOffset()).isEqualTo(3);
assertThat(issue.projectKey()).isEqualTo("projectKey");
assertThat(issue.gap()).isEqualTo(3.0);
assertThat(issue.severity()).isEqualTo("MAJOR");
}
@Test
public void nullValues() {
rawIssue = createIssueWithoutFields();
issue = new DefaultFilterableIssue(mockedProject, rawIssue, component);
assertThat(issue.line()).isNull();
assertThat(issue.gap()).isNull();
}
}
| 3,194 | 33.354839 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DefaultIssueFilterChainTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.issue;
import org.junit.Test;
import org.sonar.api.scan.issue.filter.FilterableIssue;
import org.sonar.api.scan.issue.filter.IssueFilter;
import org.sonar.api.scan.issue.filter.IssueFilterChain;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
public class DefaultIssueFilterChainTest {
private final FilterableIssue issue = mock(FilterableIssue.class);
@Test
public void should_accept_when_no_filter() {
assertThat(new DefaultIssueFilterChain().accept(issue)).isTrue();
}
static class PassingFilter implements IssueFilter {
@Override
public boolean accept(FilterableIssue issue, IssueFilterChain chain) {
return chain.accept(issue);
}
}
static class AcceptingFilter implements IssueFilter {
@Override
public boolean accept(FilterableIssue issue, IssueFilterChain chain) {
return true;
}
}
static class RefusingFilter implements IssueFilter {
@Override
public boolean accept(FilterableIssue issue, IssueFilterChain chain) {
return false;
}
}
static class FailingFilter implements IssueFilter {
@Override
public boolean accept(FilterableIssue issue, IssueFilterChain chain) {
fail();
return false;
}
}
@Test
public void should_accept_if_all_filters_pass() {
assertThat(new DefaultIssueFilterChain(
new PassingFilter(),
new PassingFilter(),
new PassingFilter()
).accept(issue)).isTrue();
}
@Test
public void should_accept_and_not_go_further_if_filter_accepts() {
assertThat(new DefaultIssueFilterChain(
new PassingFilter(),
new AcceptingFilter(),
new FailingFilter()
).accept(issue)).isTrue();
}
@Test
public void should_refuse_and_not_go_further_if_filter_refuses() {
assertThat(new DefaultIssueFilterChain(
new PassingFilter(),
new RefusingFilter(),
new FailingFilter()
).accept(issue)).isFalse();
}
}
| 2,877 | 28.979167 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuePublisherTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.issue;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.junit.MockitoJUnitRunner;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.batch.rule.internal.NewActiveRule;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.issue.internal.DefaultExternalIssue;
import org.sonar.api.batch.sensor.issue.internal.DefaultIssue;
import org.sonar.api.batch.sensor.issue.internal.DefaultIssueLocation;
import org.sonar.api.batch.sensor.issue.internal.DefaultMessageFormatting;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.FlowType;
import org.sonar.scanner.report.ReportPublisher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.api.batch.sensor.issue.MessageFormatting.Type.CODE;
@RunWith(MockitoJUnitRunner.class)
public class IssuePublisherTest {
static final RuleKey JAVA_RULE_KEY = RuleKey.of("java", "AvoidCycle");
private static final RuleKey NOSONAR_RULE_KEY = RuleKey.of("java", "NoSonarCheck");
private DefaultInputProject project;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
public IssueFilters filters = mock(IssueFilters.class);
private final ActiveRulesBuilder activeRulesBuilder = new ActiveRulesBuilder();
private IssuePublisher moduleIssues;
private final DefaultInputFile file = new TestInputFileBuilder("foo", "src/Foo.php").initMetadata("Foo\nBar\nBiz\n").build();
private final ReportPublisher reportPublisher = mock(ReportPublisher.class, RETURNS_DEEP_STUBS);
@Before
public void prepare() throws IOException {
project = new DefaultInputProject(ProjectDefinition.create()
.setKey("foo")
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder()));
activeRulesBuilder.addRule(new NewActiveRule.Builder()
.setRuleKey(JAVA_RULE_KEY)
.setSeverity(Severity.INFO)
.setQProfileKey("qp-1")
.build());
initModuleIssues();
}
@Test
public void ignore_null_active_rule() {
RuleKey INACTIVE_RULE_KEY = RuleKey.of("repo", "inactive");
initModuleIssues();
DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo"))
.forRule(INACTIVE_RULE_KEY);
boolean added = moduleIssues.initAndAddIssue(issue);
assertThat(added).isFalse();
verifyNoInteractions(reportPublisher);
}
@Test
public void ignore_null_rule_of_active_rule() {
initModuleIssues();
DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo"))
.forRule(JAVA_RULE_KEY);
boolean added = moduleIssues.initAndAddIssue(issue);
assertThat(added).isFalse();
verifyNoInteractions(reportPublisher);
}
@Test
public void add_issue_to_cache() {
initModuleIssues();
final String ruleDescriptionContextKey = "spring";
DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo"))
.forRule(JAVA_RULE_KEY)
.overrideSeverity(org.sonar.api.batch.rule.Severity.CRITICAL)
.setQuickFixAvailable(true)
.setRuleDescriptionContextKey(ruleDescriptionContextKey)
.setCodeVariants(List.of("variant1", "variant2"));
when(filters.accept(any(InputComponent.class), any(ScannerReport.Issue.class))).thenReturn(true);
boolean added = moduleIssues.initAndAddIssue(issue);
assertThat(added).isTrue();
ArgumentCaptor<ScannerReport.Issue> argument = ArgumentCaptor.forClass(ScannerReport.Issue.class);
verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.scannerId()), argument.capture());
assertThat(argument.getValue().getSeverity()).isEqualTo(org.sonar.scanner.protocol.Constants.Severity.CRITICAL);
assertThat(argument.getValue().getQuickFixAvailable()).isTrue();
assertThat(argument.getValue().getRuleDescriptionContextKey()).isEqualTo(ruleDescriptionContextKey);
assertThat(argument.getValue().getCodeVariantsList()).containsExactly("variant1", "variant2");
}
@Test
public void add_issue_flows_to_cache() {
initModuleIssues();
DefaultMessageFormatting messageFormatting = new DefaultMessageFormatting().start(0).end(4).type(CODE);
DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file))
// Flow without type
.addFlow(List.of(new DefaultIssueLocation().on(file).at(file.selectLine(1)).message("Foo1", List.of(messageFormatting)),
new DefaultIssueLocation().on(file).at(file.selectLine(2)).message("Foo2")))
// Flow with type and description
.addFlow(List.of(new DefaultIssueLocation().on(file)), NewIssue.FlowType.DATA, "description")
// Flow with execution type and no description
.addFlow(List.of(new DefaultIssueLocation().on(file)), NewIssue.FlowType.EXECUTION, null)
.forRule(JAVA_RULE_KEY);
when(filters.accept(any(InputComponent.class), any(ScannerReport.Issue.class))).thenReturn(true);
moduleIssues.initAndAddIssue(issue);
ArgumentCaptor<ScannerReport.Issue> argument = ArgumentCaptor.forClass(ScannerReport.Issue.class);
verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.scannerId()), argument.capture());
List<ScannerReport.Flow> writtenFlows = argument.getValue().getFlowList();
assertThat(writtenFlows)
.extracting(ScannerReport.Flow::getDescription, ScannerReport.Flow::getType)
.containsExactly(tuple("", FlowType.UNDEFINED), tuple("description", FlowType.DATA), tuple("", FlowType.EXECUTION));
assertThat(writtenFlows.get(0).getLocationCount()).isEqualTo(2);
assertThat(writtenFlows.get(0).getLocationList()).containsExactly(
ScannerReport.IssueLocation.newBuilder()
.setComponentRef(file.scannerId())
.setMsg("Foo1")
.addMsgFormatting(ScannerReport.MessageFormatting.newBuilder().setStart(0).setEnd(4).setType(ScannerReport.MessageFormattingType.CODE).build())
.setTextRange(ScannerReport.TextRange.newBuilder().setStartLine(1).setEndLine(1).setEndOffset(3).build())
.build(),
ScannerReport.IssueLocation.newBuilder()
.setComponentRef(file.scannerId())
.setMsg("Foo2")
.setTextRange(ScannerReport.TextRange.newBuilder().setStartLine(2).setEndLine(2).setEndOffset(3).build())
.build());
}
@Test
public void add_external_issue_to_cache() {
initModuleIssues();
DefaultExternalIssue issue = new DefaultExternalIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo"))
.type(RuleType.BUG)
.forRule(JAVA_RULE_KEY)
.severity(org.sonar.api.batch.rule.Severity.CRITICAL);
moduleIssues.initAndAddExternalIssue(issue);
ArgumentCaptor<ScannerReport.ExternalIssue> argument = ArgumentCaptor.forClass(ScannerReport.ExternalIssue.class);
verify(reportPublisher.getWriter()).appendComponentExternalIssue(eq(file.scannerId()), argument.capture());
assertThat(argument.getValue().getSeverity()).isEqualTo(org.sonar.scanner.protocol.Constants.Severity.CRITICAL);
}
@Test
public void use_severity_from_active_rule_if_no_severity_on_issue() {
initModuleIssues();
DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo"))
.forRule(JAVA_RULE_KEY);
when(filters.accept(any(InputComponent.class), any(ScannerReport.Issue.class))).thenReturn(true);
moduleIssues.initAndAddIssue(issue);
ArgumentCaptor<ScannerReport.Issue> argument = ArgumentCaptor.forClass(ScannerReport.Issue.class);
verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.scannerId()), argument.capture());
assertThat(argument.getValue().getSeverity()).isEqualTo(org.sonar.scanner.protocol.Constants.Severity.INFO);
}
@Test
public void filter_issue() {
DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message(""))
.forRule(JAVA_RULE_KEY);
when(filters.accept(any(InputComponent.class), any(ScannerReport.Issue.class))).thenReturn(false);
boolean added = moduleIssues.initAndAddIssue(issue);
assertThat(added).isFalse();
verifyNoInteractions(reportPublisher);
}
@Test
public void should_ignore_lines_commented_with_nosonar() {
initModuleIssues();
DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message(""))
.forRule(JAVA_RULE_KEY);
file.noSonarAt(new HashSet<>(Collections.singletonList(3)));
boolean added = moduleIssues.initAndAddIssue(issue);
assertThat(added).isFalse();
verifyNoInteractions(reportPublisher);
}
@Test
public void should_accept_issues_on_no_sonar_rules() {
// The "No Sonar" rule logs violations on the lines that are flagged with "NOSONAR" !!
activeRulesBuilder.addRule(new NewActiveRule.Builder()
.setRuleKey(NOSONAR_RULE_KEY)
.setSeverity(Severity.INFO)
.setQProfileKey("qp-1")
.build());
initModuleIssues();
file.noSonarAt(new HashSet<>(Collections.singletonList(3)));
DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message(""))
.forRule(NOSONAR_RULE_KEY);
when(filters.accept(any(InputComponent.class), any(ScannerReport.Issue.class))).thenReturn(true);
boolean added = moduleIssues.initAndAddIssue(issue);
assertThat(added).isTrue();
verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.scannerId()), any());
}
/**
* Every rules and active rules has to be added in builders before creating IssuePublisher
*/
private void initModuleIssues() {
moduleIssues = new IssuePublisher(activeRulesBuilder.build(), filters, reportPublisher);
}
}
| 11,857 | 41.049645 | 151 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/EnforceIssuesFilterTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.issue.ignore;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.internal.DefaultActiveRules;
import org.sonar.api.batch.rule.internal.NewActiveRule;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.scan.issue.filter.IssueFilterChain;
import org.sonar.scanner.issue.DefaultFilterableIssue;
import org.sonar.scanner.issue.ignore.pattern.IssueInclusionPatternInitializer;
import org.sonar.scanner.issue.ignore.pattern.IssuePattern;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
public class EnforceIssuesFilterTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private final IssueInclusionPatternInitializer exclusionPatternInitializer = mock(IssueInclusionPatternInitializer.class);
private final DefaultFilterableIssue issue = mock(DefaultFilterableIssue.class);
private final IssueFilterChain chain = mock(IssueFilterChain.class);
private final AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class);
private EnforceIssuesFilter ignoreFilter;
@Before
public void init() {
when(chain.accept(issue)).thenReturn(true);
}
@Test
public void shouldPassToChainIfNoConfiguredPatterns() {
DefaultActiveRules activeRules = new DefaultActiveRules(ImmutableSet.of());
ignoreFilter = new EnforceIssuesFilter(exclusionPatternInitializer, analysisWarnings, activeRules);
assertThat(ignoreFilter.accept(issue, chain)).isTrue();
verify(chain).accept(issue);
}
@Test
public void shouldPassToChainIfRuleDoesNotMatch() {
DefaultActiveRules activeRules = new DefaultActiveRules(ImmutableSet.of());
RuleKey ruleKey = RuleKey.of("repo", "rule");
when(issue.ruleKey()).thenReturn(ruleKey);
IssuePattern matching = new IssuePattern("**", "unknown");
when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(ImmutableList.of(matching));
ignoreFilter = new EnforceIssuesFilter(exclusionPatternInitializer, analysisWarnings, activeRules);
assertThat(ignoreFilter.accept(issue, chain)).isTrue();
verify(chain).accept(issue);
}
@Test
public void shouldAcceptIssueIfFullyMatched() {
DefaultActiveRules activeRules = new DefaultActiveRules(ImmutableSet.of());
String path = "org/sonar/api/Issue.java";
RuleKey ruleKey = RuleKey.of("repo", "rule");
when(issue.ruleKey()).thenReturn(ruleKey);
IssuePattern matching = new IssuePattern(path, ruleKey.toString());
when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(ImmutableList.of(matching));
when(issue.getComponent()).thenReturn(createComponentWithPath(path));
ignoreFilter = new EnforceIssuesFilter(exclusionPatternInitializer, analysisWarnings, activeRules);
assertThat(ignoreFilter.accept(issue, chain)).isTrue();
verifyNoInteractions(chain);
}
@Test
public void shouldAcceptIssueIfMatchesDeprecatedRuleKey() {
RuleKey ruleKey = RuleKey.of("repo", "rule");
DefaultActiveRules activeRules = new DefaultActiveRules(ImmutableSet.of(new NewActiveRule.Builder()
.setRuleKey(ruleKey)
.setDeprecatedKeys(singleton(RuleKey.of("repo2", "deprecated")))
.build()));
String path = "org/sonar/api/Issue.java";
when(issue.ruleKey()).thenReturn(ruleKey);
IssuePattern matching = new IssuePattern("org/**", "repo2:deprecated");
when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(ImmutableList.of(matching));
when(issue.getComponent()).thenReturn(createComponentWithPath(path));
ignoreFilter = new EnforceIssuesFilter(exclusionPatternInitializer, analysisWarnings, activeRules);
assertThat(ignoreFilter.accept(issue, chain)).isTrue();
verify(analysisWarnings)
.addUnique("A multicriteria issue enforce uses the rule key 'repo2:deprecated' that has been changed. The pattern should be updated to 'repo:rule'");
verifyNoInteractions(chain);
}
private InputComponent createComponentWithPath(String path) {
return new TestInputFileBuilder("", path).build();
}
@Test
public void shouldRefuseIssueIfRuleMatchesButNotPath() {
DefaultActiveRules activeRules = new DefaultActiveRules(ImmutableSet.of());
String path = "org/sonar/api/Issue.java";
String componentKey = "org.sonar.api.Issue";
RuleKey ruleKey = RuleKey.of("repo", "rule");
when(issue.ruleKey()).thenReturn(ruleKey);
when(issue.componentKey()).thenReturn(componentKey);
IssuePattern matching = new IssuePattern("no match", "repo:rule");
when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(ImmutableList.of(matching));
when(issue.getComponent()).thenReturn(createComponentWithPath(path));
ignoreFilter = new EnforceIssuesFilter(exclusionPatternInitializer, analysisWarnings, activeRules);
assertThat(ignoreFilter.accept(issue, chain)).isFalse();
verifyNoInteractions(chain, analysisWarnings);
}
@Test
public void shouldRefuseIssueIfRuleMatchesAndNotFile() throws IOException {
DefaultActiveRules activeRules = new DefaultActiveRules(ImmutableSet.of());
String path = "org/sonar/api/Issue.java";
RuleKey ruleKey = RuleKey.of("repo", "key");
when(issue.ruleKey()).thenReturn(ruleKey);
IssuePattern matching = new IssuePattern(path, ruleKey.toString());
when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(ImmutableList.of(matching));
when(issue.getComponent()).thenReturn(TestInputFileBuilder.newDefaultInputProject("foo", tempFolder.newFolder()));
ignoreFilter = new EnforceIssuesFilter(exclusionPatternInitializer, analysisWarnings, activeRules);
assertThat(ignoreFilter.accept(issue, chain)).isFalse();
verifyNoInteractions(chain, analysisWarnings);
}
}
| 7,162 | 43.76875 | 155 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/IgnoreIssuesFilterTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.issue.ignore;
import com.google.common.collect.ImmutableSet;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.rule.internal.DefaultActiveRules;
import org.sonar.api.batch.rule.internal.NewActiveRule;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.scan.issue.filter.IssueFilterChain;
import org.sonar.api.utils.WildcardPattern;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.issue.DefaultFilterableIssue;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
public class IgnoreIssuesFilterTest {
@Rule
public LogTester logTester = new LogTester();
private final DefaultFilterableIssue issue = mock(DefaultFilterableIssue.class);
private final IssueFilterChain chain = mock(IssueFilterChain.class);
private final AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class);
private final RuleKey ruleKey = RuleKey.of("foo", "bar");
private DefaultInputFile component;
@Before
public void prepare() {
component = mock(DefaultInputFile.class);
when(issue.getComponent()).thenReturn(component);
when(issue.ruleKey()).thenReturn(ruleKey);
}
@Test
public void shouldPassToChainIfMatcherHasNoPatternForIssue() {
DefaultActiveRules activeRules = new DefaultActiveRules(ImmutableSet.of());
IgnoreIssuesFilter underTest = new IgnoreIssuesFilter(activeRules, analysisWarnings);
when(chain.accept(issue)).thenReturn(true);
assertThat(underTest.accept(issue, chain)).isTrue();
verify(chain).accept(any());
}
@Test
public void shouldRejectIfRulePatternMatches() {
DefaultActiveRules activeRules = new DefaultActiveRules(ImmutableSet.of());
IgnoreIssuesFilter underTest = new IgnoreIssuesFilter(activeRules, analysisWarnings);
WildcardPattern pattern = mock(WildcardPattern.class);
when(pattern.match(ruleKey.toString())).thenReturn(true);
underTest.addRuleExclusionPatternForComponent(component, pattern);
assertThat(underTest.accept(issue, chain)).isFalse();
verifyNoInteractions(analysisWarnings);
}
@Test
public void shouldRejectIfRulePatternMatchesDeprecatedRule() {
DefaultActiveRules activeRules = new DefaultActiveRules(ImmutableSet.of(new NewActiveRule.Builder()
.setRuleKey(ruleKey)
.setDeprecatedKeys(singleton(RuleKey.of("repo", "rule")))
.build()));
IgnoreIssuesFilter underTest = new IgnoreIssuesFilter(activeRules, analysisWarnings);
WildcardPattern pattern = WildcardPattern.create("repo:rule");
underTest.addRuleExclusionPatternForComponent(component, pattern);
assertThat(underTest.accept(issue, chain)).isFalse();
verify(analysisWarnings).addUnique("A multicriteria issue exclusion uses the rule key 'repo:rule' that has been changed. The pattern should be updated to 'foo:bar'");
assertThat(logTester.logs())
.contains("A multicriteria issue exclusion uses the rule key 'repo:rule' that has been changed. The pattern should be updated to 'foo:bar'");
}
@Test
public void shouldAcceptIfRulePatternDoesNotMatch() {
DefaultActiveRules activeRules = new DefaultActiveRules(ImmutableSet.of());
IgnoreIssuesFilter underTest = new IgnoreIssuesFilter(activeRules, analysisWarnings);
WildcardPattern pattern = mock(WildcardPattern.class);
when(pattern.match(ruleKey.toString())).thenReturn(false);
underTest.addRuleExclusionPatternForComponent(component, pattern);
assertThat(underTest.accept(issue, chain)).isFalse();
}
}
| 4,762 | 40.780702 | 170 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssueExclusionPatternInitializerTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.issue.ignore.pattern;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
import org.sonar.core.config.IssueExclusionProperties;
import static org.assertj.core.api.Assertions.assertThat;
public class IssueExclusionPatternInitializerTest {
private IssueExclusionPatternInitializer patternsInitializer;
private MapSettings settings;
@Before
public void init() {
settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, IssueExclusionProperties.all()));
}
@Test
public void testNoConfiguration() {
patternsInitializer = new IssueExclusionPatternInitializer(settings.asConfig());
assertThat(patternsInitializer.hasConfiguredPatterns()).isFalse();
assertThat(patternsInitializer.getMulticriteriaPatterns()).isEmpty();
}
@Test(expected = MessageException.class)
public void shouldLogInvalidResourceKey() {
settings.setProperty("sonar.issue.ignore" + ".multicriteria", "1");
settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".1." + "resourceKey", "");
settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".1." + "ruleKey", "*");
patternsInitializer = new IssueExclusionPatternInitializer(settings.asConfig());
}
@Test(expected = MessageException.class)
public void shouldLogInvalidRuleKey() {
settings.setProperty("sonar.issue.ignore" + ".multicriteria", "1");
settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".1." + "resourceKey", "*");
settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".1." + "ruleKey", "");
patternsInitializer = new IssueExclusionPatternInitializer(settings.asConfig());
}
@Test
public void shouldReturnBlockPattern() {
settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY, "1,2,3");
settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".1." + IssueExclusionProperties.BEGIN_BLOCK_REGEXP, "// SONAR-OFF");
settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".1." + IssueExclusionProperties.END_BLOCK_REGEXP, "// SONAR-ON");
settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".2." + IssueExclusionProperties.BEGIN_BLOCK_REGEXP, "// FOO-OFF");
settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".2." + IssueExclusionProperties.END_BLOCK_REGEXP, "// FOO-ON");
settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".3." + IssueExclusionProperties.BEGIN_BLOCK_REGEXP, "// IGNORE-TO-EOF");
settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".3." + IssueExclusionProperties.END_BLOCK_REGEXP, "");
patternsInitializer = new IssueExclusionPatternInitializer(settings.asConfig());
assertThat(patternsInitializer.hasConfiguredPatterns()).isTrue();
assertThat(patternsInitializer.hasFileContentPattern()).isTrue();
assertThat(patternsInitializer.hasMulticriteriaPatterns()).isFalse();
assertThat(patternsInitializer.getMulticriteriaPatterns()).isEmpty();
assertThat(patternsInitializer.getBlockPatterns()).hasSize(3);
assertThat(patternsInitializer.getAllFilePatterns()).isEmpty();
}
@Test(expected = MessageException.class)
public void shouldLogInvalidStartBlockPattern() {
settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY, "1");
settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".1." + IssueExclusionProperties.BEGIN_BLOCK_REGEXP, "");
settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".1." + IssueExclusionProperties.END_BLOCK_REGEXP, "// SONAR-ON");
patternsInitializer = new IssueExclusionPatternInitializer(settings.asConfig());
}
@Test
public void shouldReturnAllFilePattern() {
settings.setProperty(IssueExclusionProperties.PATTERNS_ALLFILE_KEY, "1,2");
settings.setProperty(IssueExclusionProperties.PATTERNS_ALLFILE_KEY + ".1." + IssueExclusionProperties.FILE_REGEXP, "@SONAR-IGNORE-ALL");
settings.setProperty(IssueExclusionProperties.PATTERNS_ALLFILE_KEY + ".2." + IssueExclusionProperties.FILE_REGEXP, "//FOO-IGNORE-ALL");
patternsInitializer = new IssueExclusionPatternInitializer(settings.asConfig());
assertThat(patternsInitializer.hasConfiguredPatterns()).isTrue();
assertThat(patternsInitializer.hasFileContentPattern()).isTrue();
assertThat(patternsInitializer.hasMulticriteriaPatterns()).isFalse();
assertThat(patternsInitializer.getMulticriteriaPatterns()).isEmpty();
assertThat(patternsInitializer.getBlockPatterns()).isEmpty();
assertThat(patternsInitializer.getAllFilePatterns()).hasSize(2);
}
@Test(expected = MessageException.class)
public void shouldLogInvalidAllFilePattern() {
settings.setProperty(IssueExclusionProperties.PATTERNS_ALLFILE_KEY, "1");
settings.setProperty(IssueExclusionProperties.PATTERNS_ALLFILE_KEY + ".1." + IssueExclusionProperties.FILE_REGEXP, "");
patternsInitializer = new IssueExclusionPatternInitializer(settings.asConfig());
}
}
| 5,994 | 52.053097 | 144 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssueInclusionPatternInitializerTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.issue.ignore.pattern;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.core.config.IssueExclusionProperties;
import static org.assertj.core.api.Assertions.assertThat;
public class IssueInclusionPatternInitializerTest {
private IssueInclusionPatternInitializer patternsInitializer;
private MapSettings settings;
@Before
public void init() {
settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, IssueExclusionProperties.all()));
patternsInitializer = new IssueInclusionPatternInitializer(settings.asConfig());
}
@Test
public void testNoConfiguration() {
patternsInitializer.initPatterns();
assertThat(patternsInitializer.hasConfiguredPatterns()).isFalse();
}
@Test
public void shouldHavePatternsBasedOnMulticriteriaPattern() {
settings.setProperty("sonar.issue.enforce" + ".multicriteria", "1,2");
settings.setProperty("sonar.issue.enforce" + ".multicriteria" + ".1." + "resourceKey", "org/foo/Bar.java");
settings.setProperty("sonar.issue.enforce" + ".multicriteria" + ".1." + "ruleKey", "*");
settings.setProperty("sonar.issue.enforce" + ".multicriteria" + ".2." + "resourceKey", "org/foo/Hello.java");
settings.setProperty("sonar.issue.enforce" + ".multicriteria" + ".2." + "ruleKey", "checkstyle:MagicNumber");
patternsInitializer.initPatterns();
assertThat(patternsInitializer.hasConfiguredPatterns()).isTrue();
assertThat(patternsInitializer.hasMulticriteriaPatterns()).isTrue();
assertThat(patternsInitializer.getMulticriteriaPatterns()).hasSize(2);
}
}
| 2,578 | 39.936508 | 113 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssuePatternTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.issue.ignore.pattern;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.Rule;
import static org.assertj.core.api.Assertions.assertThat;
public class IssuePatternTest {
@Test
public void shouldMatchJavaFile() {
String javaFile = "org/foo/Bar.java";
assertThat(new IssuePattern("org/foo/Bar.java", "*").matchFile(javaFile)).isTrue();
assertThat(new IssuePattern("org/foo/*", "*").matchFile(javaFile)).isTrue();
assertThat(new IssuePattern("**Bar.java", "*").matchFile(javaFile)).isTrue();
assertThat(new IssuePattern("**", "*").matchFile(javaFile)).isTrue();
assertThat(new IssuePattern("org/*/?ar.java", "*").matchFile(javaFile)).isTrue();
assertThat(new IssuePattern("org/other/Hello.java", "*").matchFile(javaFile)).isFalse();
assertThat(new IssuePattern("org/foo/Hello.java", "*").matchFile(javaFile)).isFalse();
assertThat(new IssuePattern("org/*/??ar.java", "*").matchFile(javaFile)).isFalse();
assertThat(new IssuePattern("org/*/??ar.java", "*").matchFile(null)).isFalse();
assertThat(new IssuePattern("org/*/??ar.java", "*").matchFile("plop")).isFalse();
}
@Test
public void shouldMatchRule() {
RuleKey rule = Rule.create("checkstyle", "IllegalRegexp", "").ruleKey();
assertThat(new IssuePattern("*", "*").matchRule(rule)).isTrue();
assertThat(new IssuePattern("*", "checkstyle:*").matchRule(rule)).isTrue();
assertThat(new IssuePattern("*", "checkstyle:IllegalRegexp").matchRule(rule)).isTrue();
assertThat(new IssuePattern("*", "checkstyle:Illegal*").matchRule(rule)).isTrue();
assertThat(new IssuePattern("*", "*:*Illegal*").matchRule(rule)).isTrue();
assertThat(new IssuePattern("*", "pmd:IllegalRegexp").matchRule(rule)).isFalse();
assertThat(new IssuePattern("*", "pmd:*").matchRule(rule)).isFalse();
assertThat(new IssuePattern("*", "*:Foo*IllegalRegexp").matchRule(rule)).isFalse();
}
@Test
public void toString_should_include_all_fields() {
assertThat(new IssuePattern("*", "*:Foo*IllegalRegexp")).hasToString("IssuePattern{filePattern=*, rulePattern=*:Foo*IllegalRegexp}");
}
}
| 3,009 | 44.606061 | 137 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/LineRangeTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.issue.ignore.pattern;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class LineRangeTest {
@Test(expected = IllegalArgumentException.class)
public void lineRangeShouldBeOrdered() {
new LineRange(25, 12);
}
@Test
public void shouldConvertLineRangeToLines() {
LineRange range = new LineRange(12, 15);
assertThat(range.toLines()).containsOnly(12, 13, 14, 15);
}
@Test
public void shouldTestInclusionInRangeOfLines() {
LineRange range = new LineRange(12, 15);
assertThat(range.in(3)).isFalse();
assertThat(range.in(12)).isTrue();
assertThat(range.in(13)).isTrue();
assertThat(range.in(14)).isTrue();
assertThat(range.in(15)).isTrue();
assertThat(range.in(16)).isFalse();
}
@Test
public void testToString() {
assertThat(new LineRange(12, 15)).hasToString("[12-15]");
}
@Test
public void testEquals() {
LineRange range = new LineRange(12, 15);
assertThat(range)
.isEqualTo(range)
.isEqualTo(new LineRange(12, 15))
.isNotEqualTo(new LineRange(12, 2000))
.isNotEqualTo(new LineRange(1000, 2000))
.isNotNull()
.isNotEqualTo(new StringBuffer());
}
@Test
public void testHashCode() {
assertThat(new LineRange(12, 15)).hasSameHashCodeAs(new LineRange(12, 15));
}
}
| 2,202 | 28.77027 | 79 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.issue.ignore.scanner;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.scanner.issue.ignore.IgnoreIssuesFilter;
import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer;
import org.sonar.scanner.issue.ignore.pattern.IssuePattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class IssueExclusionsLoaderTest {
@Mock
private IssueExclusionPatternInitializer exclusionPatternInitializer;
private IgnoreIssuesFilter ignoreIssuesFilter;
private IssueExclusionsLoader scanner;
@Before
public void before() {
ignoreIssuesFilter = mock(IgnoreIssuesFilter.class);
MockitoAnnotations.initMocks(this);
scanner = new IssueExclusionsLoader(exclusionPatternInitializer, ignoreIssuesFilter, mock(AnalysisWarnings.class));
}
@Test
public void testToString() {
assertThat(scanner).hasToString("Issues Exclusions - Source Scanner");
}
@Test
public void createComputer() {
assertThat(scanner.createCharHandlerFor(TestInputFileBuilder.create("foo", "src/main/java/Foo.java").build())).isNull();
when(exclusionPatternInitializer.getAllFilePatterns()).thenReturn(Collections.singletonList("pattern"));
scanner = new IssueExclusionsLoader(exclusionPatternInitializer, ignoreIssuesFilter, mock(AnalysisWarnings.class));
assertThat(scanner.createCharHandlerFor(TestInputFileBuilder.create("foo", "src/main/java/Foo.java").build())).isNotNull();
}
@Test
public void populateRuleExclusionPatterns() {
IssuePattern pattern1 = new IssuePattern("org/foo/Bar*.java", "*");
IssuePattern pattern2 = new IssuePattern("org/foo/Hell?.java", "checkstyle:MagicNumber");
when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(Arrays.asList(pattern1, pattern2));
IssueExclusionsLoader loader = new IssueExclusionsLoader(exclusionPatternInitializer, ignoreIssuesFilter, mock(AnalysisWarnings.class));
DefaultInputFile file1 = TestInputFileBuilder.create("foo", "org/foo/Bar.java").build();
loader.addMulticriteriaPatterns(file1);
DefaultInputFile file2 = TestInputFileBuilder.create("foo", "org/foo/Baz.java").build();
loader.addMulticriteriaPatterns(file2);
DefaultInputFile file3 = TestInputFileBuilder.create("foo", "org/foo/Hello.java").build();
loader.addMulticriteriaPatterns(file3);
verify(ignoreIssuesFilter).addRuleExclusionPatternForComponent(file1, pattern1.getRulePattern());
verify(ignoreIssuesFilter).addRuleExclusionPatternForComponent(file3, pattern2.getRulePattern());
verifyNoMoreInteractions(ignoreIssuesFilter);
}
}
| 3,942 | 41.858696 | 140 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.issue.ignore.scanner;
import com.google.common.io.Resources;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.FileMetadata;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader.DoubleRegexpMatcher;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.Mockito.mock;
public class IssueExclusionsRegexpScannerTest {
private DefaultInputFile javaFile;
private List<Pattern> allFilePatterns;
private List<DoubleRegexpMatcher> blockPatterns;
private IssueExclusionsRegexpScanner regexpScanner;
private FileMetadata fileMetadata = new FileMetadata(mock(AnalysisWarnings.class));
@Before
public void init() {
blockPatterns = Arrays.asList(
new DoubleRegexpMatcher(Pattern.compile("// SONAR-OFF"), Pattern.compile("// SONAR-ON")),
new DoubleRegexpMatcher(Pattern.compile("// FOO-OFF"), Pattern.compile("// FOO-ON")));
allFilePatterns = Collections.singletonList(Pattern.compile("@SONAR-IGNORE-ALL"));
javaFile = TestInputFileBuilder.create("foo", "src/Foo.java").build();
regexpScanner = new IssueExclusionsRegexpScanner(javaFile, allFilePatterns, blockPatterns);
}
@Test
public void shouldDetectPatternLastLine() throws URISyntaxException, IOException {
Path filePath = getResource("file-with-single-regexp-last-line.txt");
fileMetadata.readMetadata(Files.newInputStream(filePath), UTF_8, filePath.toString(), regexpScanner);
assertThat(javaFile.isIgnoreAllIssues()).isTrue();
}
@Test
public void shouldDoNothing() throws Exception {
Path filePath = getResource("file-with-no-regexp.txt");
fileMetadata.readMetadata(Files.newInputStream(filePath), UTF_8, filePath.toString(), regexpScanner);
assertThat(javaFile.isIgnoreAllIssues()).isFalse();
}
@Test
public void shouldExcludeAllIssues() throws Exception {
Path filePath = getResource("file-with-single-regexp.txt");
fileMetadata.readMetadata(Files.newInputStream(filePath), UTF_8, filePath.toString(), regexpScanner);
assertThat(javaFile.isIgnoreAllIssues()).isTrue();
}
@Test
public void shouldExcludeAllIssuesEvenIfAlsoDoubleRegexps() throws Exception {
Path filePath = getResource("file-with-single-regexp-and-double-regexp.txt");
fileMetadata.readMetadata(Files.newInputStream(filePath), UTF_8, filePath.toString(), regexpScanner);
assertThat(javaFile.isIgnoreAllIssues()).isTrue();
}
@Test
public void shouldExcludeLines() throws Exception {
Path filePath = getResource("file-with-double-regexp.txt");
fileMetadata.readMetadata(Files.newInputStream(filePath), UTF_8, filePath.toString(), regexpScanner);
assertThat(javaFile.isIgnoreAllIssues()).isFalse();
assertThat(IntStream.rangeClosed(1, 20).noneMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
assertThat(IntStream.rangeClosed(21, 25).allMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
assertThat(IntStream.rangeClosed(26, 34).noneMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
}
@Test
public void shouldAddPatternToExcludeLinesTillTheEnd() throws Exception {
Path filePath = getResource("file-with-double-regexp-unfinished.txt");
fileMetadata.readMetadata(Files.newInputStream(filePath), UTF_8, filePath.toString(), regexpScanner);
assertThat(javaFile.isIgnoreAllIssues()).isFalse();
assertThat(IntStream.rangeClosed(1, 20).noneMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
assertThat(IntStream.rangeClosed(21, 34).allMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
}
@Test
public void shouldAddPatternToExcludeSeveralLineRanges() throws Exception {
Path filePath = getResource("file-with-double-regexp-twice.txt");
fileMetadata.readMetadata(Files.newInputStream(filePath), UTF_8, filePath.toString(), regexpScanner);
assertThat(javaFile.isIgnoreAllIssues()).isFalse();
assertThat(IntStream.rangeClosed(1, 20).noneMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
assertThat(IntStream.rangeClosed(21, 25).allMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
assertThat(IntStream.rangeClosed(26, 28).noneMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
assertThat(IntStream.rangeClosed(29, 33).allMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
}
@Test
public void shouldAddPatternToExcludeLinesWithWrongOrder() throws Exception {
Path filePath = getResource("file-with-double-regexp-wrong-order.txt");
fileMetadata.readMetadata(Files.newInputStream(filePath), UTF_8, filePath.toString(), regexpScanner);
assertThat(IntStream.rangeClosed(1, 24).noneMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
assertThat(IntStream.rangeClosed(25, 35).allMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
}
@Test
public void shouldAddPatternToExcludeLinesWithMess() throws Exception {
Path filePath = getResource("file-with-double-regexp-mess.txt");
fileMetadata.readMetadata(Files.newInputStream(filePath), UTF_8, filePath.toString(), regexpScanner);
assertThat(IntStream.rangeClosed(1, 20).noneMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
assertThat(IntStream.rangeClosed(21, 29).allMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
assertThat(IntStream.rangeClosed(30, 37).noneMatch(javaFile::isIgnoreAllIssuesOnLine)).isTrue();
}
private Path getResource(String fileName) throws URISyntaxException {
return Paths.get(Resources.getResource("org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/" + fileName).toURI());
}
}
| 6,953 | 44.75 | 139 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/notifications/DefaultAnalysisWarningsTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.notifications;
import org.junit.Test;
import org.sonar.api.utils.System2;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DefaultAnalysisWarningsTest {
private final System2 system2 = mock(System2.class);
private final DefaultAnalysisWarnings underTest = new DefaultAnalysisWarnings(system2);
@Test
public void addUnique_adds_messages_with_timestamp() {
String warning1 = "dummy warning 1";
long timestamp1 = 1L;
String warning2 = "dummy warning 2";
long timestamp2 = 2L;
when(system2.now())
.thenReturn(timestamp1)
.thenReturn(timestamp2);
underTest.addUnique(warning1);
underTest.addUnique(warning2);
assertThat(underTest.warnings())
.extracting(DefaultAnalysisWarnings.Message::getText, DefaultAnalysisWarnings.Message::getTimestamp)
.containsExactly(tuple(warning1, timestamp1), tuple(warning2, timestamp2));
}
@Test
public void addUnique_adds_same_message_once() {
String warning = "dummy warning";
underTest.addUnique(warning);
underTest.addUnique(warning);
assertThat(underTest.warnings())
.extracting(DefaultAnalysisWarnings.Message::getText)
.isEqualTo(singletonList(warning));
}
@Test(expected = IllegalArgumentException.class)
public void addUnique_fails_with_IAE_when_message_is_empty() {
underTest.addUnique("");
}
@Test
public void addUnique_preserves_order_and_takes_first_unique_item() {
String warning1 = "dummy warning 1";
long timestamp1 = 1L;
String warning2 = "dummy warning 2";
long timestamp2 = 2L;
String warning3 = "dummy warning 3";
long timestamp3 = 3L;
when(system2.now())
.thenReturn(timestamp1)
.thenReturn(timestamp2)
.thenReturn(timestamp3);
underTest.addUnique(warning1);
underTest.addUnique(warning2);
underTest.addUnique(warning3);
underTest.addUnique(warning2);
assertThat(underTest.warnings())
.extracting(DefaultAnalysisWarnings.Message::getText, DefaultAnalysisWarnings.Message::getTimestamp)
.containsExactly(
tuple(warning1, timestamp1),
tuple(warning2, timestamp2),
tuple(warning3, timestamp3)
);
}
}
| 3,258 | 31.919192 | 106 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/ModuleCoverageAndDuplicationExclusionsTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.phases;
import java.io.File;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.scanner.scan.ModuleConfiguration;
import org.sonar.scanner.scan.filesystem.ModuleCoverageAndDuplicationExclusions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ModuleCoverageAndDuplicationExclusionsTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private ModuleCoverageAndDuplicationExclusions coverageExclusions;
private File baseDir;
@Before
public void prepare() throws Exception {
baseDir = temp.newFolder();
}
@Test
public void shouldExcludeFileBasedOnPattern() {
DefaultInputFile file = TestInputFileBuilder.create("foo", new File(baseDir, "moduleA"), new File(baseDir, "moduleA/src/org/polop/File.php"))
.setProjectBaseDir(baseDir.toPath())
.build();
coverageExclusions = new ModuleCoverageAndDuplicationExclusions(mockConfig("src/org/polop/*", ""));
assertThat(coverageExclusions.isExcludedForCoverage(file)).isTrue();
}
@Test
public void shouldNotExcludeFileBasedOnPattern() {
DefaultInputFile file = TestInputFileBuilder.create("foo", new File(baseDir, "moduleA"), new File(baseDir, "moduleA/src/org/polop/File.php"))
.setProjectBaseDir(baseDir.toPath())
.build();
coverageExclusions = new ModuleCoverageAndDuplicationExclusions(mockConfig("src/org/other/*", ""));
assertThat(coverageExclusions.isExcludedForCoverage(file)).isFalse();
}
private ModuleConfiguration mockConfig(String coverageExclusions, String cpdExclusions) {
ModuleConfiguration config = mock(ModuleConfiguration.class);
when(config.getStringArray(CoreProperties.PROJECT_COVERAGE_EXCLUSIONS_PROPERTY)).thenReturn(new String[] {coverageExclusions});
when(config.getStringArray(CoreProperties.CPD_EXCLUSIONS)).thenReturn(new String[] {cpdExclusions});
return config;
}
}
| 3,058 | 39.786667 | 145 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/ModuleSensorsExecutorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.phases;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.io.IOException;
import java.util.Collections;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.SensorStrategy;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.bootstrap.ScannerPluginRepository;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.branch.BranchType;
import org.sonar.scanner.scan.filesystem.MutableFileSystem;
import org.sonar.scanner.sensor.ExecutingSensorContext;
import org.sonar.scanner.sensor.ModuleSensorContext;
import org.sonar.scanner.sensor.ModuleSensorExtensionDictionary;
import org.sonar.scanner.sensor.ModuleSensorOptimizer;
import org.sonar.scanner.sensor.ModuleSensorWrapper;
import org.sonar.scanner.sensor.ModuleSensorsExecutor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
@RunWith(DataProviderRunner.class)
public class ModuleSensorsExecutorTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
private ModuleSensorsExecutor rootModuleExecutor;
private ModuleSensorsExecutor subModuleExecutor;
private final SensorStrategy strategy = new SensorStrategy();
private final ModuleSensorWrapper perModuleSensor = mock(ModuleSensorWrapper.class);
private final ModuleSensorWrapper globalSensor = mock(ModuleSensorWrapper.class);
private final ScannerPluginRepository pluginRepository = mock(ScannerPluginRepository.class);
private final ModuleSensorContext context = mock(ModuleSensorContext.class);
private final ModuleSensorOptimizer optimizer = mock(ModuleSensorOptimizer.class);
private final ScannerPluginRepository pluginRepo = mock(ScannerPluginRepository.class);
private final MutableFileSystem fileSystem = mock(MutableFileSystem.class);
private final BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
private final ExecutingSensorContext executingSensorContext = mock(ExecutingSensorContext.class);
@Before
public void setUp() throws IOException {
when(perModuleSensor.isGlobal()).thenReturn(false);
when(perModuleSensor.shouldExecute()).thenReturn(true);
when(perModuleSensor.wrappedSensor()).thenReturn(mock(Sensor.class));
when(globalSensor.isGlobal()).thenReturn(true);
when(globalSensor.shouldExecute()).thenReturn(true);
when(globalSensor.wrappedSensor()).thenReturn(mock(Sensor.class));
ModuleSensorExtensionDictionary selector = mock(ModuleSensorExtensionDictionary.class);
when(selector.selectSensors(false)).thenReturn(Collections.singleton(perModuleSensor));
when(selector.selectSensors(true)).thenReturn(Collections.singleton(globalSensor));
ProjectDefinition childDef = ProjectDefinition.create().setKey("sub").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder());
ProjectDefinition rootDef = ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder());
DefaultInputModule rootModule = TestInputFileBuilder.newDefaultInputModule(rootDef);
DefaultInputModule subModule = TestInputFileBuilder.newDefaultInputModule(childDef);
InputModuleHierarchy hierarchy = mock(InputModuleHierarchy.class);
when(hierarchy.isRoot(rootModule)).thenReturn(true);
rootModuleExecutor = new ModuleSensorsExecutor(selector, rootModule, hierarchy, strategy, pluginRepository, executingSensorContext);
subModuleExecutor = new ModuleSensorsExecutor(selector, subModule, hierarchy, strategy, pluginRepository, executingSensorContext);
}
@Test
public void should_not_execute_global_sensor_for_submodule() {
subModuleExecutor.execute();
verify(perModuleSensor).analyse();
verify(perModuleSensor).wrappedSensor();
verifyNoInteractions(globalSensor);
verifyNoMoreInteractions(perModuleSensor, globalSensor);
}
@Test
public void should_execute_all_sensors_for_root_module() {
rootModuleExecutor.execute();
verify(globalSensor).wrappedSensor();
verify(perModuleSensor).wrappedSensor();
verify(globalSensor).analyse();
verify(perModuleSensor).analyse();
verify(executingSensorContext, times(2)).setSensorExecuting(any());
verify(executingSensorContext, times(2)).clearExecutingSensor();
verifyNoMoreInteractions(perModuleSensor, globalSensor, executingSensorContext);
}
@Test
@UseDataProvider("sensorsOnlyChangedInPR")
public void should_restrict_filesystem_when_pull_request_and_expected_sensor(String sensorName) throws IOException {
when(branchConfiguration.branchType()).thenReturn(BranchType.PULL_REQUEST);
ModuleSensorsExecutor executor = createModuleExecutor(sensorName);
executor.execute();
verify(fileSystem, times(2)).setRestrictToChangedFiles(true);
assertThat(logTester.logs().stream().anyMatch(
p -> p.contains(String.format("Sensor %s is restricted to changed files only", sensorName)))
).isTrue();
}
@Test
@UseDataProvider("sensorsOnlyChangedInPR")
public void should_not_restrict_filesystem_when_branch(String sensorName) throws IOException {
when(branchConfiguration.branchType()).thenReturn(BranchType.BRANCH);
ModuleSensorsExecutor executor = createModuleExecutor(sensorName);
executor.execute();
verify(fileSystem, times(2)).setRestrictToChangedFiles(false);
assertThat(logTester.logs().stream().anyMatch(
p -> p.contains(String.format("Sensor %s is restricted to changed files only", sensorName)))
).isFalse();
}
@Test
public void should_not_restrict_filesystem_when_pull_request_and_non_expected_sensor() throws IOException {
String sensorName = "NonRestrictedSensor";
when(branchConfiguration.branchType()).thenReturn(BranchType.PULL_REQUEST);
ModuleSensorsExecutor executor = createModuleExecutor(sensorName);
executor.execute();
verify(fileSystem, times(2)).setRestrictToChangedFiles(false);
assertThat(logTester.logs().stream().anyMatch(
p -> p.contains(String.format("Sensor %s is restricted to changed files only", sensorName)))
).isFalse();
}
@DataProvider
public static Object[][] sensorsOnlyChangedInPR() {
return new Object[][] {DefaultSensorDescriptor.HARDCODED_INDEPENDENT_FILE_SENSORS.toArray()};
}
private ModuleSensorsExecutor createModuleExecutor(String sensorName) throws IOException {
Sensor sensor = new TestSensor(sensorName);
ModuleSensorWrapper sensorWrapper = new ModuleSensorWrapper(sensor, context, optimizer, fileSystem, branchConfiguration);
ModuleSensorExtensionDictionary selector = mock(ModuleSensorExtensionDictionary.class);
when(selector.selectSensors(false)).thenReturn(Collections.singleton(sensorWrapper));
when(selector.selectSensors(true)).thenReturn(Collections.singleton(sensorWrapper));
ProjectDefinition rootDef = ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder());
DefaultInputModule rootModule = TestInputFileBuilder.newDefaultInputModule(rootDef);
InputModuleHierarchy hierarchy = mock(InputModuleHierarchy.class);
when(hierarchy.isRoot(rootModule)).thenReturn(true);
return new ModuleSensorsExecutor(selector, rootModule, hierarchy, strategy, pluginRepo, executingSensorContext);
}
private static class TestSensor implements Sensor {
private final String name;
public TestSensor(String name) {
this.name = name;
}
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name(name);
}
@Override
public void execute(SensorContext context) {
}
}
}
| 9,511 | 41.275556 | 136 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/PostJobsExecutorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.phases;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.sonar.scanner.bootstrap.PostJobExtensionDictionary;
import org.sonar.scanner.postjob.PostJobWrapper;
import org.sonar.scanner.postjob.PostJobsExecutor;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class PostJobsExecutorTest {
private PostJobsExecutor executor;
private PostJobExtensionDictionary selector = mock(PostJobExtensionDictionary.class);
private PostJobWrapper job1 = mock(PostJobWrapper.class);
private PostJobWrapper job2 = mock(PostJobWrapper.class);
@Before
public void setUp() {
executor = new PostJobsExecutor(selector);
}
@Test
public void should_execute_post_jobs() {
when(selector.selectPostJobs()).thenReturn(Arrays.asList(job1, job2));
when(job1.shouldExecute()).thenReturn(true);
executor.execute();
verify(job1).shouldExecute();
verify(job2).shouldExecute();
verify(job1).execute();
verifyNoMoreInteractions(job1, job2);
}
}
| 2,011 | 33.689655 | 87 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/ProjectCoverageExclusionsTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.phases;
import java.io.File;
import java.nio.file.LinkOption;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.scanner.scan.ProjectConfiguration;
import org.sonar.scanner.scan.filesystem.ProjectCoverageAndDuplicationExclusions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ProjectCoverageExclusionsTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private ProjectCoverageAndDuplicationExclusions underTest;
private File baseDir;
@Before
public void prepare() throws Exception {
baseDir = temp.newFolder().toPath().toRealPath(LinkOption.NOFOLLOW_LINKS).toFile();
}
@Test
public void shouldExcludeFileCoverageBasedOnPattern() {
DefaultInputFile file = TestInputFileBuilder.create("foo", new File(baseDir, "moduleA"), new File(baseDir, "moduleA/src/org/polop/File.php"))
.setProjectBaseDir(baseDir.toPath())
.build();
underTest = new ProjectCoverageAndDuplicationExclusions(mockConfig("moduleA/src/org/polop/*", ""));
assertThat(underTest.isExcludedForCoverage(file)).isTrue();
assertThat(underTest.isExcludedForDuplication(file)).isFalse();
}
@Test
public void shouldNotExcludeFileCoverageBasedOnPattern() {
DefaultInputFile file = TestInputFileBuilder.create("foo", new File(baseDir, "moduleA"), new File(baseDir, "moduleA/src/org/polop/File.php"))
.setProjectBaseDir(baseDir.toPath())
.build();
underTest = new ProjectCoverageAndDuplicationExclusions(mockConfig("moduleA/src/org/other/*", ""));
assertThat(underTest.isExcludedForCoverage(file)).isFalse();
assertThat(underTest.isExcludedForDuplication(file)).isFalse();
}
@Test
public void shouldExcludeFileDuplicationBasedOnPattern() {
DefaultInputFile file = TestInputFileBuilder.create("foo", new File(baseDir, "moduleA"), new File(baseDir, "moduleA/src/org/polop/File.php"))
.setProjectBaseDir(baseDir.toPath())
.build();
underTest = new ProjectCoverageAndDuplicationExclusions(mockConfig("", "moduleA/src/org/polop/*"));
assertThat(underTest.isExcludedForCoverage(file)).isFalse();
assertThat(underTest.isExcludedForDuplication(file)).isTrue();
}
@Test
public void shouldNotExcludeFileDuplicationBasedOnPattern() {
DefaultInputFile file = TestInputFileBuilder.create("foo", new File(baseDir, "moduleA"), new File(baseDir, "moduleA/src/org/polop/File.php"))
.setProjectBaseDir(baseDir.toPath())
.build();
underTest = new ProjectCoverageAndDuplicationExclusions(mockConfig("", "moduleA/src/org/other/*"));
assertThat(underTest.isExcludedForCoverage(file)).isFalse();
assertThat(underTest.isExcludedForDuplication(file)).isFalse();
}
private ProjectConfiguration mockConfig(String coverageExclusions, String cpdExclusions) {
ProjectConfiguration config = mock(ProjectConfiguration.class);
when(config.getStringArray(CoreProperties.PROJECT_COVERAGE_EXCLUSIONS_PROPERTY)).thenReturn(new String[] {coverageExclusions});
when(config.getStringArray(CoreProperties.CPD_EXCLUSIONS)).thenReturn(new String[] {cpdExclusions});
return config;
}
}
| 4,300 | 42.444444 | 145 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/platform/DefaultServerTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.platform;
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.Version;
import org.sonar.core.platform.SonarQubeVersion;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DefaultServerTest {
@Test
public void shouldLoadServerProperties() {
MapSettings settings = new MapSettings();
settings.setProperty(CoreProperties.SERVER_ID, "123");
settings.setProperty(CoreProperties.SERVER_STARTTIME, "2010-05-18T17:59:00+0000");
DefaultScannerWsClient client = mock(DefaultScannerWsClient.class);
when(client.baseUrl()).thenReturn("http://foo.com");
DefaultServer metadata = new DefaultServer((settings).asConfig(), client, new SonarQubeVersion(Version.parse("2.2")));
assertThat(metadata.getId()).isEqualTo("123");
assertThat(metadata.getVersion()).isEqualTo("2.2");
assertThat(metadata.getStartedAt()).isNotNull();
assertThat(metadata.getPublicRootUrl()).isEqualTo("http://foo.com");
assertThat(metadata.getPermanentServerId()).isEqualTo("123");
assertThat(metadata.getContextPath()).isNull();
assertThat(metadata.isSecured()).isFalse();
}
@Test
public void publicRootUrl() {
MapSettings settings = new MapSettings();
DefaultScannerWsClient client = mock(DefaultScannerWsClient.class);
when(client.baseUrl()).thenReturn("http://foo.com/");
DefaultServer metadata = new DefaultServer(settings.asConfig(), client, null);
settings.setProperty(CoreProperties.SERVER_BASE_URL, "http://server.com/");
assertThat(metadata.getPublicRootUrl()).isEqualTo("http://server.com");
settings.removeProperty(CoreProperties.SERVER_BASE_URL);
assertThat(metadata.getPublicRootUrl()).isEqualTo("http://foo.com");
}
@Test(expected = RuntimeException.class)
public void invalid_startup_date_throws_exception() {
MapSettings settings = new MapSettings();
settings.setProperty(CoreProperties.SERVER_STARTTIME, "invalid");
DefaultScannerWsClient client = mock(DefaultScannerWsClient.class);
DefaultServer metadata = new DefaultServer(settings.asConfig(), client, null);
metadata.getStartedAt();
}
}
| 3,213 | 40.205128 | 122 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/postjob/DefaultPostJobContextTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.postjob;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultPostJobContextTest {
private DefaultPostJobContext context;
private MapSettings settings;
private Configuration configuration;
@Before
public void setUp() {
settings = new MapSettings();
configuration = settings.asConfig();
context = new DefaultPostJobContext(configuration);
}
@Test
public void getConfig() {
assertThat(context.config()).isEqualTo(configuration);
}
}
| 1,506 | 31.06383 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/postjob/PostJobOptimizerTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.postjob;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.postjob.internal.DefaultPostJobDescriptor;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
public class PostJobOptimizerTest {
private PostJobOptimizer optimizer;
private MapSettings settings;
@Before
public void prepare() {
settings = new MapSettings();
}
@Test
public void should_run_analyzer_with_no_metadata() {
DefaultPostJobDescriptor descriptor = new DefaultPostJobDescriptor();
optimizer = new PostJobOptimizer(settings.asConfig());
assertThat(optimizer.shouldExecute(descriptor)).isTrue();
}
@Test
public void should_optimize_on_settings() {
DefaultPostJobDescriptor descriptor = new DefaultPostJobDescriptor()
.requireProperty("sonar.foo.reportPath");
optimizer = new PostJobOptimizer(settings.asConfig());
assertThat(optimizer.shouldExecute(descriptor)).isFalse();
settings.setProperty("sonar.foo.reportPath", "foo");
optimizer = new PostJobOptimizer(settings.asConfig());
assertThat(optimizer.shouldExecute(descriptor)).isTrue();
}
}
| 2,036 | 33.525424 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/qualitygate/QualityGateCheckTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.qualitygate;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
import org.slf4j.event.Level;
import org.sonar.api.utils.MessageException;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.report.CeTaskReportDataHolder;
import org.sonar.scanner.scan.ScanProperties;
import org.sonarqube.ws.Ce;
import org.sonarqube.ws.Ce.TaskStatus;
import org.sonarqube.ws.Qualitygates;
import org.sonarqube.ws.Qualitygates.ProjectStatusResponse.Status;
import org.sonarqube.ws.client.HttpException;
import org.sonarqube.ws.client.MockWsResponse;
import org.sonarqube.ws.client.WsRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(DataProviderRunner.class)
public class QualityGateCheckTest {
private DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class, Mockito.RETURNS_DEEP_STUBS);
private GlobalAnalysisMode analysisMode = mock(GlobalAnalysisMode.class);
private CeTaskReportDataHolder reportMetadataHolder = mock(CeTaskReportDataHolder.class);
private ScanProperties properties = mock(ScanProperties.class);
@Rule
public LogTester logTester = new LogTester();
QualityGateCheck underTest = new QualityGateCheck(wsClient, analysisMode, reportMetadataHolder, properties);
@Before
public void before() {
logTester.setLevel(Level.DEBUG);
when(reportMetadataHolder.getCeTaskId()).thenReturn("task-1234");
when(reportMetadataHolder.getDashboardUrl()).thenReturn("http://dashboard-url.com");
}
@Test
public void should_pass_if_quality_gate_ok() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(properties.qualityGateWaitTimeout()).thenReturn(5);
MockWsResponse ceTaskWsResponse = getCeTaskWsResponse(TaskStatus.SUCCESS);
doReturn(ceTaskWsResponse).when(wsClient).call(newGetCeTaskRequest());
MockWsResponse qualityGateResponse = getQualityGateWsResponse(Status.OK);
doReturn(qualityGateResponse).when(wsClient).call(newGetQualityGateRequest());
underTest.start();
underTest.await();
underTest.stop();
assertThat(logTester.logs())
.containsOnly(
"Waiting for the analysis report to be processed (max 5s)",
"QUALITY GATE STATUS: PASSED - View details on http://dashboard-url.com");
}
@Test
public void should_wait_and_then_pass_if_quality_gate_ok() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(properties.qualityGateWaitTimeout()).thenReturn(10);
MockWsResponse pendingTask = getCeTaskWsResponse(TaskStatus.PENDING);
MockWsResponse successTask = getCeTaskWsResponse(TaskStatus.SUCCESS);
doReturn(pendingTask, successTask).when(wsClient).call(newGetCeTaskRequest());
MockWsResponse qualityGateResponse = getQualityGateWsResponse(Status.OK);
doReturn(qualityGateResponse).when(wsClient).call(newGetQualityGateRequest());
underTest.start();
underTest.await();
assertThat(logTester.logs())
.contains("QUALITY GATE STATUS: PASSED - View details on http://dashboard-url.com");
}
@Test
public void should_fail_if_quality_gate_none() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(properties.qualityGateWaitTimeout()).thenReturn(5);
MockWsResponse ceTaskWsResponse = getCeTaskWsResponse(TaskStatus.SUCCESS);
doReturn(ceTaskWsResponse).when(wsClient).call(newGetCeTaskRequest());
MockWsResponse qualityGateResponse = getQualityGateWsResponse(Status.ERROR);
doReturn(qualityGateResponse).when(wsClient).call(newGetQualityGateRequest());
underTest.start();
assertThatThrownBy(() -> underTest.await())
.isInstanceOf(MessageException.class)
.hasMessage("QUALITY GATE STATUS: FAILED - View details on http://dashboard-url.com");
}
@Test
public void should_fail_if_quality_gate_error() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(properties.qualityGateWaitTimeout()).thenReturn(5);
MockWsResponse ceTaskWsResponse = getCeTaskWsResponse(TaskStatus.SUCCESS);
doReturn(ceTaskWsResponse).when(wsClient).call(newGetCeTaskRequest());
MockWsResponse qualityGateResponse = getQualityGateWsResponse(Status.ERROR);
doReturn(qualityGateResponse).when(wsClient).call(newGetQualityGateRequest());
underTest.start();
assertThatThrownBy(() -> underTest.await())
.isInstanceOf(MessageException.class)
.hasMessage("QUALITY GATE STATUS: FAILED - View details on http://dashboard-url.com");
}
@Test
public void should_wait_and_then_fail_if_quality_gate_error() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(properties.qualityGateWaitTimeout()).thenReturn(10);
MockWsResponse pendingTask = getCeTaskWsResponse(TaskStatus.PENDING);
MockWsResponse successTask = getCeTaskWsResponse(TaskStatus.SUCCESS);
doReturn(pendingTask, successTask).when(wsClient).call(newGetCeTaskRequest());
MockWsResponse qualityGateResponse = getQualityGateWsResponse(Status.ERROR);
doReturn(qualityGateResponse).when(wsClient).call(newGetQualityGateRequest());
underTest.start();
assertThatThrownBy(() -> underTest.await())
.isInstanceOf(MessageException.class)
.hasMessage("QUALITY GATE STATUS: FAILED - View details on http://dashboard-url.com");
}
@Test
public void should_fail_if_quality_gate_timeout_exceeded() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(properties.qualityGateWaitTimeout()).thenReturn(1);
MockWsResponse ceTaskWsResponse = getCeTaskWsResponse(TaskStatus.PENDING);
doReturn(ceTaskWsResponse).when(wsClient).call(newGetCeTaskRequest());
underTest.start();
assertThatThrownBy(() -> underTest.await())
.isInstanceOf(MessageException.class)
.hasMessage("Quality Gate check timeout exceeded - View details on http://dashboard-url.com");
}
@Test
public void should_fail_if_cant_call_ws_for_quality_gate() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(properties.qualityGateWaitTimeout()).thenReturn(5);
MockWsResponse ceTaskWsResponse = getCeTaskWsResponse(TaskStatus.SUCCESS);
doReturn(ceTaskWsResponse).when(wsClient).call(newGetCeTaskRequest());
doThrow(new HttpException("quality-gate-url", 400, "content")).when(wsClient).call(newGetQualityGateRequest());
underTest.start();
assertThatThrownBy(() -> underTest.await())
.isInstanceOf(MessageException.class)
.hasMessage("Failed to get Quality Gate status - HTTP code 400: content");
}
@Test
public void should_fail_if_invalid_response_from_quality_gate_ws() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(properties.qualityGateWaitTimeout()).thenReturn(5);
MockWsResponse ceTaskWsResponse = getCeTaskWsResponse(TaskStatus.SUCCESS);
doReturn(ceTaskWsResponse).when(wsClient).call(newGetCeTaskRequest());
MockWsResponse qualityGateResponse = new MockWsResponse();
qualityGateResponse.setRequestUrl("quality-gate-url");
qualityGateResponse.setContent("blabla");
doReturn(qualityGateResponse).when(wsClient).call(newGetQualityGateRequest());
underTest.start();
assertThatThrownBy(() -> underTest.await())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to parse response from quality-gate-url");
}
@Test
public void should_fail_if_cant_call_ws_for_task() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(properties.qualityGateWaitTimeout()).thenReturn(5);
when(wsClient.call(newGetCeTaskRequest())).thenThrow(new HttpException("task-url", 400, "content"));
underTest.start();
assertThatThrownBy(() -> underTest.await())
.isInstanceOf(MessageException.class)
.hasMessage("Failed to get CE Task status - HTTP code 400: content");
}
@Test
public void should_fail_if_invalid_response_from_ws_task() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(properties.qualityGateWaitTimeout()).thenReturn(5);
MockWsResponse getCeTaskRequest = new MockWsResponse();
getCeTaskRequest.setRequestUrl("ce-task-url");
getCeTaskRequest.setContent("blabla");
when(wsClient.call(newGetCeTaskRequest())).thenReturn(getCeTaskRequest);
underTest.start();
assertThatThrownBy(() -> underTest.await())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to parse response from ce-task-url");
}
@Test
@UseDataProvider("ceTaskNotSucceededStatuses")
public void should_fail_if_task_not_succeeded(TaskStatus taskStatus) {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(properties.qualityGateWaitTimeout()).thenReturn(5);
MockWsResponse ceTaskWsResponse = getCeTaskWsResponse(taskStatus);
when(wsClient.call(newGetCeTaskRequest())).thenReturn(ceTaskWsResponse);
underTest.start();
assertThatThrownBy(() -> underTest.await())
.isInstanceOf(MessageException.class)
.hasMessageContaining("CE Task finished abnormally with status: " + taskStatus.name());
}
private WsRequest newGetCeTaskRequest() {
return argThat(new WsRequestPathMatcher("api/ce/task"));
}
private MockWsResponse getCeTaskWsResponse(TaskStatus status) {
MockWsResponse submitMockResponse = new MockWsResponse();
submitMockResponse.setContent(Ce.TaskResponse.newBuilder()
.setTask(Ce.Task.newBuilder().setStatus(status))
.build()
.toByteArray());
return submitMockResponse;
}
@Test
public void should_skip_wait_if_disabled() {
when(properties.shouldWaitForQualityGate()).thenReturn(false);
underTest.start();
underTest.await();
assertThat(logTester.logs())
.contains("Quality Gate check disabled - skipping");
}
@Test
public void should_fail_if_enabled_with_medium_test() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
when(analysisMode.isMediumTest()).thenReturn(true);
underTest.start();
assertThatThrownBy(() -> underTest.await())
.isInstanceOf(IllegalStateException.class);
}
private WsRequest newGetQualityGateRequest() {
return argThat(new WsRequestPathMatcher("api/qualitygates/project_status"));
}
private MockWsResponse getQualityGateWsResponse(Status status) {
MockWsResponse qualityGateWsResponse = new MockWsResponse();
qualityGateWsResponse.setContent(Qualitygates.ProjectStatusResponse.newBuilder()
.setProjectStatus(Qualitygates.ProjectStatusResponse.ProjectStatus.newBuilder()
.setStatus(status)
.build())
.build()
.toByteArray());
return qualityGateWsResponse;
}
@DataProvider
public static Object[][] ceTaskNotSucceededStatuses() {
return new Object[][] {
{TaskStatus.CANCELED},
{TaskStatus.FAILED},
};
}
private static class WsRequestPathMatcher implements ArgumentMatcher<WsRequest> {
String path;
WsRequestPathMatcher(String path) {
this.path = path;
}
@Override
public boolean matches(WsRequest right) {
return path.equals(right.getPath());
}
}
}
| 12,681 | 35.973761 | 115 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ActiveRulesPublisherTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.rule.internal.DefaultActiveRules;
import org.sonar.api.batch.rule.internal.NewActiveRule;
import org.sonar.api.rule.RuleKey;
import org.sonar.core.util.CloseableIterator;
import org.sonar.scanner.protocol.Constants;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
public class ActiveRulesPublisherTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void write() throws Exception {
File outputDir = temp.newFolder();
FileStructure fileStructure = new FileStructure(outputDir);
ScannerReportWriter writer = new ScannerReportWriter(fileStructure);
NewActiveRule ar = new NewActiveRule.Builder()
.setRuleKey(RuleKey.of("java", "S001"))
.setSeverity("BLOCKER")
.setParam("p1", "v1")
.setCreatedAt(1_000L)
.setUpdatedAt(2_000L)
.setQProfileKey("qp1")
.build();
ActiveRules activeRules = new DefaultActiveRules(singletonList(ar));
ActiveRulesPublisher underTest = new ActiveRulesPublisher(activeRules);
underTest.publish(writer);
ScannerReportReader reader = new ScannerReportReader(fileStructure);
try (CloseableIterator<ScannerReport.ActiveRule> readIt = reader.readActiveRules()) {
ScannerReport.ActiveRule reportAr = readIt.next();
assertThat(reportAr.getRuleRepository()).isEqualTo("java");
assertThat(reportAr.getRuleKey()).isEqualTo("S001");
assertThat(reportAr.getSeverity()).isEqualTo(Constants.Severity.BLOCKER);
assertThat(reportAr.getCreatedAt()).isEqualTo(1_000L);
assertThat(reportAr.getUpdatedAt()).isEqualTo(2_000L);
assertThat(reportAr.getQProfileKey()).isEqualTo("qp1");
assertThat(reportAr.getParamsByKeyMap()).hasSize(1);
assertThat(reportAr.getParamsByKeyMap().entrySet().iterator().next().getKey()).isEqualTo("p1");
assertThat(reportAr.getParamsByKeyMap().entrySet().iterator().next().getValue()).isEqualTo("v1");
assertThat(readIt.hasNext()).isFalse();
}
}
}
| 3,322 | 40.024691 | 103 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/AnalysisCachePublisherTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.scanner.cache.ScannerWriteCache;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class AnalysisCachePublisherTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private final ScannerWriteCache writeCache = mock(ScannerWriteCache.class);
private final AnalysisCachePublisher publisher = new AnalysisCachePublisher(writeCache);
private ScannerReportWriter scannerReportWriter;
@Before
public void before() throws IOException {
FileStructure fileStructure = new FileStructure(temp.newFolder());
scannerReportWriter = new ScannerReportWriter(fileStructure);
}
@Test
public void publish_closes_cache() {
publisher.publish(scannerReportWriter);
verify(writeCache).close();
}
}
| 1,922 | 33.963636 | 90 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/AnalysisContextReportPublisherTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.utils.System2;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.core.platform.PluginInfo;
import org.sonar.scanner.bootstrap.GlobalServerSettings;
import org.sonar.scanner.bootstrap.ScannerPluginRepository;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.scan.ProjectServerSettings;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import org.sonar.updatecenter.common.Version;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
public class AnalysisContextReportPublisherTest {
private static final String SONAR_SKIP = "sonar.skip";
private static final String COM_FOO = "com.foo";
@Rule
public LogTester logTester = new LogTester();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private final ScannerPluginRepository pluginRepo = mock(ScannerPluginRepository.class);
private final System2 system2 = mock(System2.class);
private final GlobalServerSettings globalServerSettings = mock(GlobalServerSettings.class);
private final InputModuleHierarchy hierarchy = mock(InputModuleHierarchy.class);
private final InputComponentStore store = mock(InputComponentStore.class);
private final ProjectServerSettings projectServerSettings = mock(ProjectServerSettings.class);
private final AnalysisContextReportPublisher publisher = new AnalysisContextReportPublisher(projectServerSettings, pluginRepo, system2, globalServerSettings, hierarchy, store);
private ScannerReportWriter writer;
@Before
public void prepare() throws IOException {
logTester.setLevel(LoggerLevel.INFO);
FileStructure fileStructure = new FileStructure(temp.newFolder());
writer = new ScannerReportWriter(fileStructure);
when(system2.properties()).thenReturn(new Properties());
}
@Test
public void shouldOnlyDumpPluginsByDefault() throws Exception {
when(pluginRepo.getExternalPluginsInfos()).thenReturn(singletonList(new PluginInfo("xoo").setName("Xoo").setVersion(Version.create("1.0"))));
DefaultInputModule rootModule = new DefaultInputModule(ProjectDefinition.create()
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder()));
when(store.allModules()).thenReturn(singletonList(rootModule));
when(hierarchy.root()).thenReturn(rootModule);
publisher.init(writer);
assertThat(writer.getFileStructure().analysisLog()).exists();
assertThat(FileUtils.readFileToString(writer.getFileStructure().analysisLog(), StandardCharsets.UTF_8)).contains("Xoo 1.0 (xoo)");
verifyNoInteractions(system2);
}
@Test
public void dumpServerSideGlobalProps() throws Exception {
logTester.setLevel(LoggerLevel.DEBUG);
when(globalServerSettings.properties()).thenReturn(ImmutableMap.of(COM_FOO, "bar", SONAR_SKIP, "true"));
DefaultInputModule rootModule = new DefaultInputModule(ProjectDefinition.create()
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder())
.setProperty("sonar.projectKey", "foo"));
when(store.allModules()).thenReturn(singletonList(rootModule));
when(hierarchy.root()).thenReturn(rootModule);
publisher.init(writer);
String content = FileUtils.readFileToString(writer.getFileStructure().analysisLog(), StandardCharsets.UTF_8);
assertThat(content)
.containsOnlyOnce(COM_FOO)
.containsOnlyOnce(SONAR_SKIP);
}
@Test
public void dumpServerSideProjectProps() throws Exception {
logTester.setLevel(LoggerLevel.DEBUG);
DefaultInputModule rootModule = new DefaultInputModule(ProjectDefinition.create()
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder())
.setProperty("sonar.projectKey", "foo"));
when(store.allModules()).thenReturn(singletonList(rootModule));
when(hierarchy.root()).thenReturn(rootModule);
when(projectServerSettings.properties()).thenReturn(ImmutableMap.of(COM_FOO, "bar", SONAR_SKIP, "true"));
publisher.init(writer);
List<String> lines = FileUtils.readLines(writer.getFileStructure().analysisLog(), StandardCharsets.UTF_8);
assertThat(lines).containsExactly(
"Plugins:",
"Bundled analyzers:",
"Global server settings:",
"Project server settings:",
" - com.foo=bar",
" - sonar.skip=true",
"Project scanner properties:",
" - sonar.projectKey=foo");
}
@Test
public void shouldNotDumpSensitiveModuleProperties() throws Exception {
DefaultInputModule rootModule = new DefaultInputModule(ProjectDefinition.create()
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder())
.setProperty("sonar.projectKey", "foo")
.setProperty("sonar.projectKey", "foo")
.setProperty("sonar.login", "my_token")
.setProperty("sonar.password", "azerty")
.setProperty("sonar.cpp.license.secured", "AZERTY"));
when(store.allModules()).thenReturn(singletonList(rootModule));
when(hierarchy.root()).thenReturn(rootModule);
publisher.init(writer);
assertThat(writer.getFileStructure().analysisLog()).exists();
assertThat(FileUtils.readFileToString(writer.getFileStructure().analysisLog(), StandardCharsets.UTF_8)).containsSubsequence(
"sonar.cpp.license.secured=******",
"sonar.login=******",
"sonar.password=******",
"sonar.projectKey=foo");
}
@Test
public void shouldShortenModuleProperties() throws Exception {
File baseDir = temp.newFolder();
DefaultInputModule rootModule = new DefaultInputModule(ProjectDefinition.create()
.setBaseDir(baseDir)
.setWorkDir(temp.newFolder())
.setProperty("sonar.projectKey", "foo")
.setProperty("sonar.projectBaseDir", baseDir.toString())
.setProperty("sonar.aVeryLongProp", StringUtils.repeat("abcde", 1000)));
when(store.allModules()).thenReturn(singletonList(rootModule));
when(hierarchy.root()).thenReturn(rootModule);
publisher.init(writer);
assertThat(writer.getFileStructure().analysisLog()).exists();
assertThat(FileUtils.readFileToString(writer.getFileStructure().analysisLog(), StandardCharsets.UTF_8)).containsSubsequence(
"sonar.aVeryLongProp=" + StringUtils.repeat("abcde", 199) + "ab...",
"sonar.projectBaseDir=" + baseDir,
"sonar.projectKey=foo");
}
// SONAR-7598
@Test
public void shouldNotDumpSensitiveGlobalProperties() throws Exception {
when(globalServerSettings.properties()).thenReturn(ImmutableMap.of("sonar.login", "my_token", "sonar.password", "azerty", "sonar.cpp.license.secured", "AZERTY"));
DefaultInputModule rootModule = new DefaultInputModule(ProjectDefinition.create()
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder())
.setProperty("sonar.projectKey", "foo"));
when(store.allModules()).thenReturn(singletonList(rootModule));
when(hierarchy.root()).thenReturn(rootModule);
publisher.init(writer);
assertThat(FileUtils.readFileToString(writer.getFileStructure().analysisLog(), StandardCharsets.UTF_8)).containsSubsequence(
"sonar.cpp.license.secured=******",
"sonar.login=******",
"sonar.password=******");
}
// SONAR-7371
@Test
public void dontDumpParentProps() throws Exception {
logTester.setLevel(LoggerLevel.DEBUG);
DefaultInputModule module = new DefaultInputModule(ProjectDefinition.create()
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder())
.setProperty("sonar.projectKey", "foo")
.setProperty(SONAR_SKIP, "true"));
DefaultInputModule parent = new DefaultInputModule(ProjectDefinition.create()
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder())
.setProperty("sonar.projectKey", "parent")
.setProperty(SONAR_SKIP, "true"));
when(hierarchy.parent(module)).thenReturn(parent);
when(store.allModules()).thenReturn(Arrays.asList(parent, module));
when(hierarchy.root()).thenReturn(parent);
publisher.init(writer);
List<String> lines = FileUtils.readLines(writer.getFileStructure().analysisLog(), StandardCharsets.UTF_8);
assertThat(lines).containsExactly(
"Plugins:",
"Bundled analyzers:",
"Global server settings:",
"Project server settings:",
"Project scanner properties:",
" - sonar.projectKey=parent",
" - sonar.skip=true",
"Scanner properties of module: foo",
" - sonar.projectKey=foo"
);
}
@Test
public void init_splitsPluginsByTypeInTheFile() throws IOException {
DefaultInputModule parent = new DefaultInputModule(ProjectDefinition.create()
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder())
.setProperty("sonar.projectKey", "parent")
.setProperty(SONAR_SKIP, "true"));
when(hierarchy.root()).thenReturn(parent);
when(pluginRepo.getExternalPluginsInfos()).thenReturn(List.of(new PluginInfo("xoo").setName("Xoo").setVersion(Version.create("1.0"))));
when(pluginRepo.getBundledPluginsInfos()).thenReturn(List.of(new PluginInfo("java").setName("Java").setVersion(Version.create("9.7"))));
publisher.init(writer);
List<String> lines = FileUtils.readLines(writer.getFileStructure().analysisLog(), StandardCharsets.UTF_8);
System.out.println(lines);
assertThat(lines).contains("Plugins:",
" - Xoo 1.0 (xoo)",
"Bundled analyzers:",
" - Java 9.7 (java)");
}
}
| 11,075 | 40.174721 | 178 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/AnalysisWarningsPublisherTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import com.google.common.collect.Lists;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.utils.System2;
import org.sonar.scanner.notifications.DefaultAnalysisWarnings;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class AnalysisWarningsPublisherTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private final DefaultAnalysisWarnings analysisWarnings = new DefaultAnalysisWarnings(mock(System2.class));
private final AnalysisWarningsPublisher underTest = new AnalysisWarningsPublisher(analysisWarnings);
private FileStructure fileStructure;
@Before
public void setUp() throws IOException {
fileStructure = new FileStructure(temp.newFolder());
}
@Test
public void publish_warnings() throws IOException {
ScannerReportWriter writer = new ScannerReportWriter(fileStructure);
String warning1 = "warning 1";
String warning2 = "warning 2";
analysisWarnings.addUnique(warning1);
analysisWarnings.addUnique(warning1);
analysisWarnings.addUnique(warning2);
underTest.publish(writer);
ScannerReportReader reader = new ScannerReportReader(fileStructure);
List<ScannerReport.AnalysisWarning> warnings = Lists.newArrayList(reader.readAnalysisWarnings());
assertThat(warnings)
.extracting(ScannerReport.AnalysisWarning::getText)
.containsExactly(warning1, warning2);
}
@Test
public void do_not_write_warnings_report_when_empty() throws IOException {
File outputDir = temp.newFolder();
ScannerReportWriter writer = new ScannerReportWriter(fileStructure);
underTest.publish(writer);
assertThat(writer.getFileStructure().analysisWarnings()).doesNotExist();
ScannerReportReader reader = new ScannerReportReader(fileStructure);
List<ScannerReport.AnalysisWarning> warnings = Lists.newArrayList(reader.readAnalysisWarnings());
assertThat(warnings).isEmpty();
}
}
| 3,213 | 35.11236 | 108 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/CeTaskReportDataHolderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class CeTaskReportDataHolderTest {
CeTaskReportDataHolder underTest = new CeTaskReportDataHolder();
@Test
public void should_initialize_field() {
String ceTaskId = "ceTaskId";
String ceTaskUrl = "ceTaskUrl";
String dashboardUrl = "dashboardUrl";
underTest.init(ceTaskId, ceTaskUrl, dashboardUrl);
assertThat(underTest.getCeTaskId()).isEqualTo(ceTaskId);
assertThat(underTest.getCeTaskUrl()).isEqualTo(ceTaskUrl);
assertThat(underTest.getDashboardUrl()).isEqualTo(dashboardUrl);
}
@Test
public void getCeTaskId_should_fail_if_not_initialized() {
assertThatThrownBy(() -> underTest.getCeTaskId())
.isInstanceOf(IllegalStateException.class);
}
@Test
public void getCeTaskUrl_should_fail_if_not_initialized() {
assertThatThrownBy(() -> underTest.getCeTaskUrl())
.isInstanceOf(IllegalStateException.class);
}
@Test
public void getDashboardUrl_should_fail_if_not_initialized() {
assertThatThrownBy(() -> underTest.getDashboardUrl())
.isInstanceOf(IllegalStateException.class);
}
}
| 2,098 | 33.983333 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ChangedLinesPublisherTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.repository.ReferenceBranchSupplier;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import org.sonar.scanner.scm.ScmConfiguration;
import org.sonar.scm.git.GitScmProvider;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assumptions.assumeThat;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
public class ChangedLinesPublisherTest {
private static final String TARGET_BRANCH = "target";
private static final Path BASE_DIR = Paths.get("/root");
private final ScmConfiguration scmConfiguration = mock(ScmConfiguration.class);
private final InputModuleHierarchy inputModuleHierarchy = mock(InputModuleHierarchy.class);
private final InputComponentStore inputComponentStore = mock(InputComponentStore.class);
private final BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
private final ReferenceBranchSupplier referenceBranchSupplier = mock(ReferenceBranchSupplier.class);
private ScannerReportWriter writer;
private FileStructure fileStructure;
private final ScmProvider provider = mock(ScmProvider.class);
private final DefaultInputProject project = mock(DefaultInputProject.class);
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
private final ChangedLinesPublisher publisher = new ChangedLinesPublisher(scmConfiguration, project, inputComponentStore, branchConfiguration, referenceBranchSupplier);
@Before
public void setUp() {
fileStructure = new FileStructure(temp.getRoot());
writer = new ScannerReportWriter(fileStructure);
when(branchConfiguration.isPullRequest()).thenReturn(true);
when(scmConfiguration.isDisabled()).thenReturn(false);
when(scmConfiguration.provider()).thenReturn(provider);
when(branchConfiguration.targetBranchName()).thenReturn(TARGET_BRANCH);
when(project.getBaseDir()).thenReturn(BASE_DIR);
}
@Test
public void skip_if_scm_is_disabled() {
when(scmConfiguration.isDisabled()).thenReturn(true);
publisher.publish(writer);
verifyNoInteractions(inputComponentStore, inputModuleHierarchy, provider);
assertNotPublished();
}
@Test
public void skip_if_not_pr() {
when(branchConfiguration.isPullRequest()).thenReturn(false);
publisher.publish(writer);
verifyNoInteractions(inputComponentStore, inputModuleHierarchy, provider);
assertNotPublished();
}
@Test
public void skip_if_target_branch_is_null() {
when(branchConfiguration.targetBranchName()).thenReturn(null);
publisher.publish(writer);
verifyNoInteractions(inputComponentStore, inputModuleHierarchy, provider);
assertNotPublished();
}
@Test
public void skip_if_no_scm_provider() {
when(scmConfiguration.provider()).thenReturn(null);
publisher.publish(writer);
verifyNoInteractions(inputComponentStore, inputModuleHierarchy, provider);
assertNotPublished();
}
@Test
public void skip_if_scm_provider_returns_null() {
publisher.publish(writer);
assertNotPublished();
}
@Test
public void write_changed_files() {
DefaultInputFile fileWithChangedLines = createInputFile("path1", "l1\nl2\nl3\n");
DefaultInputFile fileNotReturned = createInputFile("path2", "l1\nl2\nl3\n");
DefaultInputFile fileWithoutChangedLines = createInputFile("path3", "l1\nl2\nl3\n");
Set<Path> paths = new HashSet<>(Arrays.asList(BASE_DIR.resolve("path1"), BASE_DIR.resolve("path2"), BASE_DIR.resolve("path3")));
Set<Integer> lines = new HashSet<>(Arrays.asList(1, 10));
when(provider.branchChangedLines(TARGET_BRANCH, BASE_DIR, paths))
.thenReturn(ImmutableMap.of(BASE_DIR.resolve("path1"), lines, BASE_DIR.resolve("path3"), Collections.emptySet()));
when(inputComponentStore.allChangedFilesToPublish()).thenReturn(Arrays.asList(fileWithChangedLines, fileNotReturned, fileWithoutChangedLines));
publisher.publish(writer);
assertPublished(fileWithChangedLines, new HashSet<>(Arrays.asList(1, 10)));
assertPublished(fileWithoutChangedLines, Collections.emptySet());
assertPublished(fileNotReturned, Collections.emptySet());
assumeThat(logTester.logs()).contains("File '/root/path2' was detected as changed but without having changed lines");
}
@Test
public void write_changed_file_with_GitScmProvider() {
GitScmProvider provider = mock(GitScmProvider.class);
when(scmConfiguration.provider()).thenReturn(provider);
Set<Integer> lines = new HashSet<>(Arrays.asList(1, 10));
when(provider.branchChangedLines(eq(TARGET_BRANCH), eq(BASE_DIR), anySet()))
.thenReturn(ImmutableMap.of(BASE_DIR.resolve("path1"), lines, BASE_DIR.resolve("path3"), Collections.emptySet()));
publisher.publish(writer);
verify(provider).branchChangedLinesWithFileMovementDetection(eq(TARGET_BRANCH), eq(BASE_DIR), anyMap());
}
@Test
public void write_last_line_as_changed_if_all_other_lines_are_changed_and_last_line_is_empty() {
DefaultInputFile fileWithChangedLines = createInputFile("path1", "l1\nl2\nl3\n");
DefaultInputFile fileWithoutChangedLines = createInputFile("path2", "l1\nl2\nl3\n");
Set<Path> paths = new HashSet<>(Arrays.asList(BASE_DIR.resolve("path1"), BASE_DIR.resolve("path2")));
Set<Integer> lines = new HashSet<>(Arrays.asList(1, 2, 3));
when(provider.branchChangedLines(TARGET_BRANCH, BASE_DIR, paths)).thenReturn(Collections.singletonMap(BASE_DIR.resolve("path1"), lines));
when(inputComponentStore.allChangedFilesToPublish()).thenReturn(Arrays.asList(fileWithChangedLines, fileWithoutChangedLines));
publisher.publish(writer);
assertPublished(fileWithChangedLines, new HashSet<>(Arrays.asList(1, 2, 3, 4)));
assertPublished(fileWithoutChangedLines, Collections.emptySet());
}
@Test
public void do_not_write_last_line_as_changed_if_its_not_empty() {
DefaultInputFile fileWithChangedLines = createInputFile("path1", "l1\nl2\nl3\nl4");
DefaultInputFile fileWithoutChangedLines = createInputFile("path2", "l1\nl2\nl3\nl4");
Set<Path> paths = new HashSet<>(Arrays.asList(BASE_DIR.resolve("path1"), BASE_DIR.resolve("path2")));
Set<Integer> lines = new HashSet<>(Arrays.asList(1, 2, 3));
when(provider.branchChangedLines(TARGET_BRANCH, BASE_DIR, paths)).thenReturn(Collections.singletonMap(BASE_DIR.resolve("path1"), lines));
when(inputComponentStore.allChangedFilesToPublish()).thenReturn(Arrays.asList(fileWithChangedLines, fileWithoutChangedLines));
publisher.publish(writer);
assertPublished(fileWithChangedLines, new HashSet<>(Arrays.asList(1, 2, 3)));
assertPublished(fileWithoutChangedLines, Collections.emptySet());
}
private DefaultInputFile createInputFile(String path, String contents) {
return new TestInputFileBuilder("module", path)
.setContents(contents)
.setProjectBaseDir(BASE_DIR)
.setModuleBaseDir(BASE_DIR)
.build();
}
private void assertPublished(DefaultInputFile file, Set<Integer> lines) {
assertThat(new File(temp.getRoot(), "changed-lines-" + file.scannerId() + ".pb")).exists();
ScannerReportReader reader = new ScannerReportReader(fileStructure);
assertThat(reader.readComponentChangedLines(file.scannerId()).getLineList()).containsExactlyElementsOf(lines);
}
private void assertNotPublished() {
assertThat(temp.getRoot()).isEmptyDirectory();
}
}
| 9,469 | 43.460094 | 170 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ComponentsPublisherTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.CoreProperties;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.utils.DateUtils;
import org.sonar.scanner.ProjectInfo;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReport.Component;
import org.sonar.scanner.protocol.output.ScannerReport.Component.FileStatus;
import org.sonar.scanner.protocol.output.ScannerReport.ComponentLink.ComponentLinkType;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ComponentsPublisherTest {
private final SonarRuntime sonarRuntime = mock(SonarRuntime.class);
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private FileStructure fileStructure;
private ScannerReportWriter writer;
private BranchConfiguration branchConfiguration;
@Before
public void setUp() throws IOException {
branchConfiguration = mock(BranchConfiguration.class);
File outputDir = temp.newFolder();
fileStructure = new FileStructure(outputDir);
writer = new ScannerReportWriter(fileStructure);
}
@Test
public void add_components_to_report() throws Exception {
ProjectInfo projectInfo = mock(ProjectInfo.class);
when(projectInfo.getAnalysisDate()).thenReturn(DateUtils.parseDate("2012-12-12"));
ProjectDefinition rootDef = ProjectDefinition.create()
.setKey("foo")
.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, "1.0")
.setName("Root project")
.setDescription("Root description")
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder());
DefaultInputProject project = new DefaultInputProject(rootDef, 1);
InputComponentStore store = new InputComponentStore(branchConfiguration, sonarRuntime);
Path moduleBaseDir = temp.newFolder().toPath();
ProjectDefinition module1Def = ProjectDefinition.create()
.setKey("module1")
.setName("Module1")
.setDescription("Module description")
.setBaseDir(moduleBaseDir.toFile())
.setWorkDir(temp.newFolder());
rootDef.addSubProject(module1Def);
DefaultInputFile file = new TestInputFileBuilder("foo", "module1/src/Foo.java", 4).setLines(2).setStatus(InputFile.Status.SAME).build();
store.put("module1", file);
DefaultInputFile file18 = new TestInputFileBuilder("foo", "module1/src2/Foo.java", 18).setLines(2).setStatus(InputFile.Status.SAME).build();
store.put("module1", file18);
DefaultInputFile file2 = new TestInputFileBuilder("foo", "module1/src/Foo2.java", 5).setPublish(false).setLines(2).build();
store.put("module1", file2);
DefaultInputFile fileWithoutLang = new TestInputFileBuilder("foo", "module1/src/make", 6).setLines(10).setStatus(InputFile.Status.CHANGED).build();
store.put("module1", fileWithoutLang);
DefaultInputFile testFile = new TestInputFileBuilder("foo", "module1/test/FooTest.java", 7).setType(Type.TEST).setStatus(InputFile.Status.ADDED).setLines(4).build();
store.put("module1", testFile);
DefaultInputFile movedFile = new TestInputFileBuilder("foo", "module1/src/MovedFile.java", "module0/src/MovedFile.java", 9).setStatus(InputFile.Status.CHANGED).setLines(4).build();
store.put("module1", movedFile);
ComponentsPublisher publisher = new ComponentsPublisher(project, store);
publisher.publish(writer);
assertThat(writer.hasComponentData(FileStructure.Domain.COMPONENT, 1)).isTrue();
assertThat(writer.hasComponentData(FileStructure.Domain.COMPONENT, 4)).isTrue();
assertThat(writer.hasComponentData(FileStructure.Domain.COMPONENT, 6)).isTrue();
assertThat(writer.hasComponentData(FileStructure.Domain.COMPONENT, 7)).isTrue();
assertThat(writer.hasComponentData(FileStructure.Domain.COMPONENT, 9)).isTrue();
// not marked for publishing
assertThat(writer.hasComponentData(FileStructure.Domain.COMPONENT, 5)).isFalse();
// no such reference
assertThat(writer.hasComponentData(FileStructure.Domain.COMPONENT, 8)).isFalse();
ScannerReportReader reader = new ScannerReportReader(fileStructure);
Component rootProtobuf = reader.readComponent(1);
assertThat(rootProtobuf.getKey()).isEqualTo("foo");
assertThat(rootProtobuf.getDescription()).isEqualTo("Root description");
assertThat(rootProtobuf.getLinkCount()).isZero();
Component movedFileProtobuf = reader.readComponent(9);
assertThat(movedFileProtobuf.getOldRelativeFilePath()).isEqualTo("module0/src/MovedFile.java");
assertThat(reader.readComponent(4).getStatus()).isEqualTo(FileStatus.SAME);
assertThat(reader.readComponent(6).getStatus()).isEqualTo(FileStatus.CHANGED);
assertThat(reader.readComponent(7).getStatus()).isEqualTo(FileStatus.ADDED);
}
@Test
public void publish_unchanged_components_even_in_prs() throws IOException {
when(branchConfiguration.isPullRequest()).thenReturn(true);
ProjectInfo projectInfo = mock(ProjectInfo.class);
when(projectInfo.getAnalysisDate()).thenReturn(DateUtils.parseDate("2012-12-12"));
Path baseDir = temp.newFolder().toPath();
ProjectDefinition rootDef = ProjectDefinition.create()
.setKey("foo")
.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, "1.0")
.setName("Root project")
.setDescription("Root description")
.setBaseDir(baseDir.toFile())
.setWorkDir(temp.newFolder());
DefaultInputProject project = new DefaultInputProject(rootDef, 1);
InputComponentStore store = new InputComponentStore(branchConfiguration, sonarRuntime);
DefaultInputFile file = new TestInputFileBuilder("foo", "src/Foo.java", 5)
.setLines(2)
.setPublish(true)
.setStatus(InputFile.Status.ADDED)
.build();
store.put("foo", file);
DefaultInputFile file2 = new TestInputFileBuilder("foo", "src2/Foo2.java", 6)
.setPublish(true)
.setStatus(InputFile.Status.SAME)
.setLines(2)
.build();
store.put("foo", file2);
ComponentsPublisher publisher = new ComponentsPublisher(project, store);
publisher.publish(writer);
assertThat(writer.hasComponentData(FileStructure.Domain.COMPONENT, 5)).isTrue();
// do not skip, needed for computing overall coverage
assertThat(writer.hasComponentData(FileStructure.Domain.COMPONENT, 6)).isTrue();
}
@Test
public void publish_project_without_version_and_name() throws IOException {
ProjectInfo projectInfo = mock(ProjectInfo.class);
when(projectInfo.getAnalysisDate()).thenReturn(DateUtils.parseDate("2012-12-12"));
ProjectDefinition rootDef = ProjectDefinition.create()
.setKey("foo")
.setDescription("Root description")
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder());
DefaultInputProject project = new DefaultInputProject(rootDef, 1);
InputComponentStore store = new InputComponentStore(branchConfiguration, sonarRuntime);
ComponentsPublisher publisher = new ComponentsPublisher(project, store);
publisher.publish(writer);
assertThat(writer.hasComponentData(FileStructure.Domain.COMPONENT, 1)).isTrue();
ScannerReportReader reader = new ScannerReportReader(fileStructure);
Component rootProtobuf = reader.readComponent(1);
assertThat(rootProtobuf.getKey()).isEqualTo("foo");
assertThat(rootProtobuf.getName()).isEmpty();
assertThat(rootProtobuf.getDescription()).isEqualTo("Root description");
assertThat(rootProtobuf.getLinkCount()).isZero();
}
@Test
public void publish_project_with_links() throws Exception {
ProjectInfo projectInfo = mock(ProjectInfo.class);
when(projectInfo.getAnalysisDate()).thenReturn(DateUtils.parseDate("2012-12-12"));
ProjectDefinition rootDef = ProjectDefinition.create()
.setKey("foo")
.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, "1.0")
.setName("Root project")
.setProperty(CoreProperties.LINKS_HOME_PAGE, "http://home")
.setProperty(CoreProperties.LINKS_CI, "http://ci")
.setDescription("Root description")
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder());
DefaultInputProject project = new DefaultInputProject(rootDef, 1);
InputComponentStore store = new InputComponentStore(branchConfiguration, sonarRuntime);
ComponentsPublisher publisher = new ComponentsPublisher(project, store);
publisher.publish(writer);
ScannerReportReader reader = new ScannerReportReader(fileStructure);
Component rootProtobuf = reader.readComponent(1);
assertThat(rootProtobuf.getLinkCount()).isEqualTo(2);
assertThat(rootProtobuf.getLink(0).getType()).isEqualTo(ComponentLinkType.HOME);
assertThat(rootProtobuf.getLink(0).getHref()).isEqualTo("http://home");
assertThat(rootProtobuf.getLink(1).getType()).isEqualTo(ComponentLinkType.CI);
assertThat(rootProtobuf.getLink(1).getHref()).isEqualTo("http://ci");
}
}
| 10,519 | 43.201681 | 184 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ContextPropertiesPublisherTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.config.DefaultConfiguration;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.repository.ContextPropertiesCache;
import org.sonar.scanner.scm.ScmConfiguration;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ContextPropertiesPublisherTest {
private final ScannerReportWriter writer = mock(ScannerReportWriter.class);
private final ContextPropertiesCache cache = new ContextPropertiesCache();
private final DefaultConfiguration config = mock(DefaultConfiguration.class);
private final Map<String, String> props = new HashMap<>();
private final ScmConfiguration scmConfiguration = mock(ScmConfiguration.class);
private final CiConfiguration ciConfiguration = mock(CiConfiguration.class);
private final ContextPropertiesPublisher underTest = new ContextPropertiesPublisher(cache, config, scmConfiguration, ciConfiguration);
@Before
public void prepareMock() {
when(config.getProperties()).thenReturn(props);
when(ciConfiguration.getCiName()).thenReturn("undetected");
}
@Test
public void publish_writes_properties_to_report() {
cache.put("foo1", "bar1");
cache.put("foo2", "bar2");
underTest.publish(writer);
List<ScannerReport.ContextProperty> expected = Arrays.asList(
newContextProperty("foo1", "bar1"),
newContextProperty("foo2", "bar2"),
newContextProperty("sonar.analysis.detectedscm", "undetected"),
newContextProperty("sonar.analysis.detectedci", "undetected"));
expectWritten(expected);
}
@Test
public void publish_settings_prefixed_with_sonar_analysis_for_webhooks() {
props.put("foo", "should not be exported");
props.put("sonar.analysis.revision", "ab45b3");
props.put("sonar.analysis.build.number", "B123");
underTest.publish(writer);
List<ScannerReport.ContextProperty> expected = Arrays.asList(
newContextProperty("sonar.analysis.revision", "ab45b3"),
newContextProperty("sonar.analysis.build.number", "B123"),
newContextProperty("sonar.analysis.detectedscm", "undetected"),
newContextProperty("sonar.analysis.detectedci", "undetected"));
expectWritten(expected);
}
private void expectWritten(List<ScannerReport.ContextProperty> expected) {
verify(writer).writeContextProperties(argThat(props -> {
List<ScannerReport.ContextProperty> copy = Lists.newArrayList(props);
copy.removeAll(expected);
return copy.isEmpty();
}));
}
private static ScannerReport.ContextProperty newContextProperty(String key, String value) {
return ScannerReport.ContextProperty.newBuilder()
.setKey(key)
.setValue(value)
.build();
}
}
| 3,986 | 38.088235 | 136 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/JavaArchitectureInformationProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class JavaArchitectureInformationProviderTest {
private final JavaArchitectureInformationProvider javaArchitectureInformationProvider = new JavaArchitectureInformationProvider();
@Test
public void is64bitJavaVersion_whenRunningWith64bitJava_shouldReturnTrue() {
assertThat(javaArchitectureInformationProvider.is64bitJavaVersion()).isTrue();
}
}
| 1,328 | 35.916667 | 132 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/MetadataPublisherTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import com.google.common.collect.ImmutableMap;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Date;
import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.core.plugin.PluginType;
import org.sonar.scanner.ProjectInfo;
import org.sonar.scanner.bootstrap.ScannerPlugin;
import org.sonar.scanner.bootstrap.ScannerPluginRepository;
import org.sonar.scanner.cpd.CpdSettings;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.repository.ReferenceBranchSupplier;
import org.sonar.scanner.rule.QProfile;
import org.sonar.scanner.rule.QualityProfiles;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.branch.BranchType;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import org.sonar.scanner.scm.ScmConfiguration;
import org.sonar.scanner.scm.ScmRevision;
import static java.util.Collections.emptyMap;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(DataProviderRunner.class)
public class MetadataPublisherTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private MetadataPublisher underTest;
private final QualityProfiles qProfiles = mock(QualityProfiles.class);
private final ProjectInfo projectInfo = mock(ProjectInfo.class);
private final CpdSettings cpdSettings = mock(CpdSettings.class);
private final ReferenceBranchSupplier referenceBranchSupplier = mock(ReferenceBranchSupplier.class);
private final ScannerPluginRepository pluginRepository = mock(ScannerPluginRepository.class);
private BranchConfiguration branches;
private ScmConfiguration scmConfiguration;
private final ScmProvider scmProvider = mock(ScmProvider.class);
private final ScmRevision scmRevision = mock(ScmRevision.class);
private final InputComponentStore componentStore = mock(InputComponentStore.class);
private ScannerReportWriter writer;
private ScannerReportReader reader;
@Before
public void prepare() throws IOException {
FileStructure fileStructure = new FileStructure(temp.newFolder());
writer = new ScannerReportWriter(fileStructure);
reader = new ScannerReportReader(fileStructure);
when(projectInfo.getAnalysisDate()).thenReturn(new Date(1234567L));
when(scmProvider.relativePathFromScmRoot(any(Path.class))).thenReturn(Paths.get("dummy/path"));
when(scmProvider.revisionId(any(Path.class))).thenReturn("dummy-sha1");
createPublisher(ProjectDefinition.create());
when(pluginRepository.getPluginsByKey()).thenReturn(emptyMap());
}
private void createPublisher(ProjectDefinition def) throws IOException {
Path rootBaseDir = temp.newFolder().toPath();
Path moduleBaseDir = rootBaseDir.resolve("moduleDir");
Files.createDirectory(moduleBaseDir);
DefaultInputModule rootModule = new DefaultInputModule(def
.setBaseDir(rootBaseDir.toFile())
.setKey("root")
.setWorkDir(temp.newFolder()), TestInputFileBuilder.nextBatchId());
InputModuleHierarchy inputModuleHierarchy = mock(InputModuleHierarchy.class);
when(inputModuleHierarchy.root()).thenReturn(rootModule);
DefaultInputModule child = new DefaultInputModule(ProjectDefinition.create()
.setKey("module")
.setBaseDir(moduleBaseDir.toFile())
.setWorkDir(temp.newFolder()), TestInputFileBuilder.nextBatchId());
when(inputModuleHierarchy.children(rootModule)).thenReturn(Collections.singletonList(child));
when(inputModuleHierarchy.relativePathToRoot(child)).thenReturn("modulePath");
when(inputModuleHierarchy.relativePathToRoot(rootModule)).thenReturn("");
branches = mock(BranchConfiguration.class);
scmConfiguration = mock(ScmConfiguration.class);
when(scmConfiguration.provider()).thenReturn(scmProvider);
underTest = new MetadataPublisher(projectInfo, inputModuleHierarchy, qProfiles, cpdSettings,
pluginRepository, branches, scmRevision, componentStore, scmConfiguration, referenceBranchSupplier);
}
@Test
public void write_metadata() {
Date date = new Date();
when(qProfiles.findAll()).thenReturn(Collections.singletonList(new QProfile("q1", "Q1", "java", date)));
when(pluginRepository.getPluginsByKey()).thenReturn(ImmutableMap.of(
"java", new ScannerPlugin("java", 12345L, PluginType.BUNDLED, null),
"php", new ScannerPlugin("php", 45678L, PluginType.BUNDLED, null)));
when(referenceBranchSupplier.getFromProperties()).thenReturn("newCodeReference");
underTest.publish(writer);
ScannerReport.Metadata metadata = reader.readMetadata();
assertThat(metadata.getAnalysisDate()).isEqualTo(1234567L);
assertThat(metadata.getNewCodeReferenceBranch()).isEqualTo("newCodeReference");
assertThat(metadata.getProjectKey()).isEqualTo("root");
assertThat(metadata.getProjectVersion()).isEmpty();
assertThat(metadata.getNotAnalyzedFilesByLanguageCount()).isZero();
assertThat(metadata.getQprofilesPerLanguageMap()).containsOnly(entry("java", org.sonar.scanner.protocol.output.ScannerReport.Metadata.QProfile.newBuilder()
.setKey("q1")
.setName("Q1")
.setLanguage("java")
.setRulesUpdatedAt(date.getTime())
.build()));
assertThat(metadata.getPluginsByKey()).containsOnly(entry("java", org.sonar.scanner.protocol.output.ScannerReport.Metadata.Plugin.newBuilder()
.setKey("java")
.setUpdatedAt(12345)
.build()),
entry("php", org.sonar.scanner.protocol.output.ScannerReport.Metadata.Plugin.newBuilder()
.setKey("php")
.setUpdatedAt(45678)
.build()));
}
@Test
public void write_not_analysed_file_counts() {
when(componentStore.getNotAnalysedFilesByLanguage()).thenReturn(ImmutableMap.of("c", 10, "cpp", 20));
underTest.publish(writer);
ScannerReport.Metadata metadata = reader.readMetadata();
assertThat(metadata.getNotAnalyzedFilesByLanguageMap()).contains(entry("c", 10), entry("cpp", 20));
}
@Test
@UseDataProvider("projectVersions")
public void write_project_version(@Nullable String projectVersion, String expected) {
when(projectInfo.getProjectVersion()).thenReturn(Optional.ofNullable(projectVersion));
underTest.publish(writer);
ScannerReport.Metadata metadata = reader.readMetadata();
assertThat(metadata.getProjectVersion()).isEqualTo(expected);
}
@DataProvider
public static Object[][] projectVersions() {
String version = randomAlphabetic(15);
return new Object[][] {
{null, ""},
{"", ""},
{"5.6.3", "5.6.3"},
{version, version}
};
}
@Test
@UseDataProvider("buildStrings")
public void write_buildString(@Nullable String buildString, String expected) {
when(projectInfo.getBuildString()).thenReturn(Optional.ofNullable(buildString));
underTest.publish(writer);
ScannerReport.Metadata metadata = reader.readMetadata();
assertThat(metadata.getBuildString()).isEqualTo(expected);
}
@DataProvider
public static Object[][] buildStrings() {
String randomBuildString = randomAlphabetic(15);
return new Object[][] {
{null, ""},
{"", ""},
{"5.6.3", "5.6.3"},
{randomBuildString, randomBuildString}
};
}
@Test
public void write_branch_info() {
String branchName = "name";
String targetName = "target";
when(branches.branchName()).thenReturn(branchName);
when(branches.branchType()).thenReturn(BranchType.BRANCH);
when(branches.targetBranchName()).thenReturn(targetName);
underTest.publish(writer);
ScannerReport.Metadata metadata = reader.readMetadata();
assertThat(metadata.getBranchName()).isEqualTo(branchName);
assertThat(metadata.getBranchType()).isEqualTo(ScannerReport.Metadata.BranchType.BRANCH);
assertThat(metadata.getReferenceBranchName()).isEmpty();
assertThat(metadata.getTargetBranchName()).isEqualTo(targetName);
}
@Test
public void dont_write_new_code_reference_if_not_specified_in_properties() {
when(referenceBranchSupplier.get()).thenReturn("ref");
when(referenceBranchSupplier.getFromProperties()).thenReturn(null);
underTest.publish(writer);
ScannerReport.Metadata metadata = reader.readMetadata();
assertThat(metadata.getNewCodeReferenceBranch()).isEmpty();
}
@Test
public void write_project_basedir() {
String path = "some/dir";
Path relativePathFromScmRoot = Paths.get(path);
when(scmProvider.relativePathFromScmRoot(any(Path.class))).thenReturn(relativePathFromScmRoot);
underTest.publish(writer);
ScannerReport.Metadata metadata = reader.readMetadata();
assertThat(metadata.getRelativePathFromScmRoot()).isEqualTo(path);
}
@Test
public void write_revision_id() throws Exception {
String revisionId = "some-sha1";
when(scmRevision.get()).thenReturn(Optional.of(revisionId));
underTest.publish(writer);
ScannerReport.Metadata metadata = reader.readMetadata();
assertThat(metadata.getScmRevisionId()).isEqualTo(revisionId);
}
@Test
public void should_not_crash_when_scm_provider_does_not_support_relativePathFromScmRoot() {
ScmProvider fakeScmProvider = new ScmProvider() {
@Override
public String key() {
return "foo";
}
};
when(scmConfiguration.provider()).thenReturn(fakeScmProvider);
underTest.publish(writer);
ScannerReport.Metadata metadata = reader.readMetadata();
assertThat(metadata.getRelativePathFromScmRoot()).isEmpty();
}
}
| 11,439 | 39.567376 | 159 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ReportPublisherTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.slf4j.event.Level;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.impl.utils.JUnitTempFolder;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.platform.Server;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.TempFolder;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.scan.ScanProperties;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonarqube.ws.Ce;
import org.sonarqube.ws.client.HttpException;
import org.sonarqube.ws.client.MockWsResponse;
import org.sonarqube.ws.client.WsRequest;
import org.sonarqube.ws.client.WsResponse;
import static org.apache.commons.io.FileUtils.readFileToString;
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.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.scanner.report.ReportPublisher.SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE;
import static org.sonar.scanner.scan.branch.BranchType.BRANCH;
import static org.sonar.scanner.scan.branch.BranchType.PULL_REQUEST;
public class ReportPublisherTest {
@Rule
public LogTester logTester = new LogTester();
@Rule
public JUnitTempFolder reportTempFolder = new JUnitTempFolder();
private GlobalAnalysisMode mode = mock(GlobalAnalysisMode.class);
private ScanProperties properties = mock(ScanProperties.class);
private DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class, Mockito.RETURNS_DEEP_STUBS);
private Server server = mock(Server.class);
private InputModuleHierarchy moduleHierarchy = mock(InputModuleHierarchy.class);
private DefaultInputModule root;
private AnalysisContextReportPublisher contextPublisher = mock(AnalysisContextReportPublisher.class);
private BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
private CeTaskReportDataHolder reportMetadataHolder = mock(CeTaskReportDataHolder.class);
private ReportPublisher underTest;
private AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class);
private FileStructure fileStructure;
private JavaArchitectureInformationProvider javaArchitectureInformationProvider = mock(JavaArchitectureInformationProvider.class);
@Before
public void setUp() {
logTester.setLevel(Level.DEBUG);
root = new DefaultInputModule(
ProjectDefinition.create().setKey("org.sonarsource.sonarqube:sonarqube").setBaseDir(reportTempFolder.newDir()).setWorkDir(reportTempFolder.getRoot()));
when(moduleHierarchy.root()).thenReturn(root);
fileStructure = new FileStructure(reportTempFolder.getRoot());
when(server.getPublicRootUrl()).thenReturn("https://localhost");
when(server.getVersion()).thenReturn("6.4");
when(properties.metadataFilePath()).thenReturn(reportTempFolder.newDir().toPath()
.resolve("folder")
.resolve("report-task.txt"));
underTest = new ReportPublisher(properties, wsClient, server, contextPublisher, moduleHierarchy, mode, reportTempFolder,
new ReportPublisherStep[0], branchConfiguration, reportMetadataHolder, analysisWarnings, javaArchitectureInformationProvider, fileStructure);
}
@Test
public void checks_if_component_has_issues() {
underTest.getWriter().writeComponentIssues(1, List.of(ScannerReport.Issue.newBuilder().build()));
assertThat(underTest.getReader().hasIssues(1)).isTrue();
assertThat(underTest.getReader().hasIssues(2)).isFalse();
}
@Test
public void use_write_timeout_from_properties() {
when(properties.reportPublishTimeout()).thenReturn(60);
MockWsResponse submitMockResponse = new MockWsResponse();
submitMockResponse.setContent(Ce.SubmitResponse.newBuilder().setTaskId("task-1234").build().toByteArray());
when(wsClient.call(any())).thenReturn(submitMockResponse);
underTest.start();
underTest.execute();
verify(wsClient).call(argThat(req -> (req).getWriteTimeOutInMs().orElse(0) == 60_000));
}
@Test
public void should_not_log_success_when_should_wait_for_QG() {
when(properties.shouldWaitForQualityGate()).thenReturn(true);
MockWsResponse submitMockResponse = new MockWsResponse();
submitMockResponse.setContent(Ce.SubmitResponse.newBuilder().setTaskId("task-1234").build().toByteArray());
when(wsClient.call(any())).thenReturn(submitMockResponse);
underTest.start();
underTest.execute();
assertThat(logTester.logs()).noneMatch(s -> s.contains("ANALYSIS SUCCESSFUL"));
}
@Test
public void dump_information_about_report_uploading() throws IOException {
underTest.prepareAndDumpMetadata("TASK-123");
assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
"projectKey=org.sonarsource.sonarqube:sonarqube\n" +
"serverUrl=https://localhost\n" +
"serverVersion=6.4\n" +
"dashboardUrl=https://localhost/dashboard?id=org.sonarsource.sonarqube%3Asonarqube\n" +
"ceTaskId=TASK-123\n" +
"ceTaskUrl=https://localhost/api/ce/task?id=TASK-123\n");
}
@Test
public void upload_error_message() {
HttpException ex = new HttpException("url", 404, "{\"errors\":[{\"msg\":\"Organization with key 'MyOrg' does not exist\"}]}");
WsResponse response = mock(WsResponse.class);
when(response.failIfNotSuccessful()).thenThrow(ex);
when(wsClient.call(any(WsRequest.class))).thenThrow(new IllegalStateException("timeout"));
assertThatThrownBy(() -> underTest.upload(reportTempFolder.newFile()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to upload report: timeout");
}
@Test
public void parse_upload_error_message() {
HttpException ex = new HttpException("url", 404, "{\"errors\":[{\"msg\":\"Organization with key 'MyOrg' does not exist\"}]}");
WsResponse response = mock(WsResponse.class);
when(response.failIfNotSuccessful()).thenThrow(ex);
when(wsClient.call(any(WsRequest.class))).thenReturn(response);
assertThatThrownBy(() -> underTest.upload(reportTempFolder.newFile()))
.isInstanceOf(MessageException.class)
.hasMessage("Server failed to process report. Please check server logs: Organization with key 'MyOrg' does not exist");
}
@Test
public void dump_public_url_if_defined_for_main_branch() throws IOException {
when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
underTest.prepareAndDumpMetadata("TASK-123");
assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
"projectKey=org.sonarsource.sonarqube:sonarqube\n" +
"serverUrl=https://publicserver/sonarqube\n" +
"serverVersion=6.4\n" +
"dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube\n" +
"ceTaskId=TASK-123\n" +
"ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
}
@Test
public void dump_public_url_if_defined_for_branches() throws IOException {
when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
when(branchConfiguration.branchType()).thenReturn(BRANCH);
when(branchConfiguration.branchName()).thenReturn("branch-6.7");
ReportPublisher underTest = new ReportPublisher(properties, wsClient, server, contextPublisher, moduleHierarchy, mode, mock(TempFolder.class),
new ReportPublisherStep[0], branchConfiguration, reportMetadataHolder, analysisWarnings, javaArchitectureInformationProvider, fileStructure);
underTest.prepareAndDumpMetadata("TASK-123");
assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
"projectKey=org.sonarsource.sonarqube:sonarqube\n" +
"serverUrl=https://publicserver/sonarqube\n" +
"serverVersion=6.4\n" +
"dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube&branch=branch-6.7\n" +
"ceTaskId=TASK-123\n" +
"ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
}
@Test
public void dump_public_url_if_defined_for_pull_request() throws IOException {
when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
when(branchConfiguration.branchName()).thenReturn("Bitbucket cloud Widget");
when(branchConfiguration.branchType()).thenReturn(PULL_REQUEST);
when(branchConfiguration.pullRequestKey()).thenReturn("105");
ReportPublisher underTest = new ReportPublisher(properties, wsClient, server, contextPublisher, moduleHierarchy, mode, mock(TempFolder.class),
new ReportPublisherStep[0], branchConfiguration, reportMetadataHolder, analysisWarnings, javaArchitectureInformationProvider, fileStructure);
underTest.prepareAndDumpMetadata("TASK-123");
assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
"projectKey=org.sonarsource.sonarqube:sonarqube\n" +
"serverUrl=https://publicserver/sonarqube\n" +
"serverVersion=6.4\n" +
"dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube&pullRequest=105\n" +
"ceTaskId=TASK-123\n" +
"ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
}
@Test
public void fail_if_public_url_malformed() {
when(server.getPublicRootUrl()).thenReturn("invalid");
assertThatThrownBy(() -> underTest.start())
.isInstanceOf(MessageException.class)
.hasMessage("Failed to parse public URL set in SonarQube server: invalid");
}
@Test
public void should_not_dump_information_when_medium_test_enabled() {
when(mode.isMediumTest()).thenReturn(true);
underTest.start();
underTest.execute();
assertThat(logTester.logs(Level.INFO))
.contains("ANALYSIS SUCCESSFUL")
.doesNotContain("dashboard/index");
assertThat(properties.metadataFilePath()).doesNotExist();
}
@Test
public void should_upload_and_dump_information() {
when(reportMetadataHolder.getDashboardUrl()).thenReturn("https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube");
when(reportMetadataHolder.getCeTaskUrl()).thenReturn("https://publicserver/sonarqube/api/ce/task?id=TASK-123");
MockWsResponse submitMockResponse = new MockWsResponse();
submitMockResponse.setContent(Ce.SubmitResponse.newBuilder().setTaskId("task-1234").build().toByteArray());
when(wsClient.call(any())).thenReturn(submitMockResponse);
underTest.start();
underTest.execute();
assertThat(properties.metadataFilePath()).exists();
assertThat(logTester.logs(Level.DEBUG))
.contains("Report metadata written to " + properties.metadataFilePath());
assertThat(logTester.logs(Level.INFO))
.contains("ANALYSIS SUCCESSFUL, you can find the results at: https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube")
.contains("More about the report processing at https://publicserver/sonarqube/api/ce/task?id=TASK-123");
}
@Test
public void dump_information_to_custom_path() {
underTest.prepareAndDumpMetadata("TASK-123");
assertThat(properties.metadataFilePath()).exists();
assertThat(logTester.logs(Level.DEBUG)).contains("Report metadata written to " + properties.metadataFilePath());
}
@Test
public void should_not_delete_report_if_property_is_set() throws IOException {
when(properties.shouldKeepReport()).thenReturn(true);
underTest.start();
underTest.stop();
assertThat(fileStructure.root()).isDirectory();
}
@Test
public void should_delete_report_by_default() throws IOException {
underTest.start();
underTest.stop();
assertThat(fileStructure.root()).doesNotExist();
}
@Test
public void test_ws_parameters() throws Exception {
WsResponse response = mock(WsResponse.class);
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
Ce.SubmitResponse.newBuilder().build().writeTo(out);
out.close();
when(response.failIfNotSuccessful()).thenReturn(response);
when(response.contentStream()).thenReturn(in);
when(wsClient.call(any(WsRequest.class))).thenReturn(response);
underTest.upload(reportTempFolder.newFile());
ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
verify(wsClient).call(capture.capture());
WsRequest wsRequest = capture.getValue();
assertThat(wsRequest.getParameters().getKeys()).containsOnly("projectKey");
assertThat(wsRequest.getParameters().getValue("projectKey")).isEqualTo("org.sonarsource.sonarqube:sonarqube");
}
@Test
public void test_send_branches_characteristics() throws Exception {
String branchName = "feature";
when(branchConfiguration.branchName()).thenReturn(branchName);
when(branchConfiguration.branchType()).thenReturn(BRANCH);
WsResponse response = mock(WsResponse.class);
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
Ce.SubmitResponse.newBuilder().build().writeTo(out);
out.close();
when(response.failIfNotSuccessful()).thenReturn(response);
when(response.contentStream()).thenReturn(in);
when(wsClient.call(any(WsRequest.class))).thenReturn(response);
underTest.upload(reportTempFolder.newFile());
ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
verify(wsClient).call(capture.capture());
WsRequest wsRequest = capture.getValue();
assertThat(wsRequest.getParameters().getKeys()).hasSize(2);
assertThat(wsRequest.getParameters().getValues("projectKey")).containsExactly("org.sonarsource.sonarqube:sonarqube");
assertThat(wsRequest.getParameters().getValues("characteristic"))
.containsExactlyInAnyOrder("branch=" + branchName, "branchType=" + BRANCH.name());
}
@Test
public void send_pull_request_characteristic() throws Exception {
String branchName = "feature";
String pullRequestId = "pr-123";
when(branchConfiguration.branchName()).thenReturn(branchName);
when(branchConfiguration.branchType()).thenReturn(PULL_REQUEST);
when(branchConfiguration.pullRequestKey()).thenReturn(pullRequestId);
WsResponse response = mock(WsResponse.class);
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
Ce.SubmitResponse.newBuilder().build().writeTo(out);
out.close();
when(response.failIfNotSuccessful()).thenReturn(response);
when(response.contentStream()).thenReturn(in);
when(wsClient.call(any(WsRequest.class))).thenReturn(response);
underTest.upload(reportTempFolder.newFile());
ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
verify(wsClient).call(capture.capture());
WsRequest wsRequest = capture.getValue();
assertThat(wsRequest.getParameters().getKeys()).hasSize(2);
assertThat(wsRequest.getParameters().getValues("projectKey")).containsExactly("org.sonarsource.sonarqube:sonarqube");
assertThat(wsRequest.getParameters().getValues("characteristic"))
.containsExactlyInAnyOrder("pullRequest=" + pullRequestId);
}
@Test
public void test_do_not_log_or_add_warning_if_using_64bit_jre() {
when(javaArchitectureInformationProvider.is64bitJavaVersion()).thenReturn(true);
when(mode.isMediumTest()).thenReturn(true);
underTest.start();
underTest.execute();
assertThat(logTester.logs(Level.WARN)).isEmpty();
verifyNoInteractions(analysisWarnings);
}
@Test
public void test_log_and_add_warning_if_using_non64bit_jre() {
when(javaArchitectureInformationProvider.is64bitJavaVersion()).thenReturn(false);
when(mode.isMediumTest()).thenReturn(true);
underTest.start();
underTest.execute();
assertThat(logTester.logs(Level.WARN)).containsOnly(SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE);
verify(analysisWarnings).addUnique(SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE);
}
}
| 17,831 | 43.02963 | 157 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/SourcePublisherTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.report;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class SourcePublisherTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private SourcePublisher publisher;
private File sourceFile;
private ScannerReportWriter writer;
private DefaultInputFile inputFile;
@Before
public void prepare() throws IOException {
File baseDir = temp.newFolder();
sourceFile = new File(baseDir, "src/Foo.php");
String moduleKey = "foo";
inputFile = new TestInputFileBuilder(moduleKey, "src/Foo.php")
.setLines(5)
.setModuleBaseDir(baseDir.toPath())
.setCharset(StandardCharsets.ISO_8859_1)
.build();
DefaultInputProject rootProject = TestInputFileBuilder.newDefaultInputProject(moduleKey, baseDir);
InputComponentStore componentStore = new InputComponentStore(mock(BranchConfiguration.class), mock(SonarRuntime.class));
componentStore.put(moduleKey, inputFile);
publisher = new SourcePublisher(componentStore);
File outputDir = temp.newFolder();
FileStructure fileStructure = new FileStructure(outputDir);
writer = new ScannerReportWriter(fileStructure);
}
@Test
public void publishEmptySource() throws Exception {
FileUtils.write(sourceFile, "", StandardCharsets.ISO_8859_1);
publisher.publish(writer);
File out = writer.getSourceFile(inputFile.scannerId());
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEmpty();
}
@Test
public void publishSourceWithLastEmptyLine() throws Exception {
FileUtils.write(sourceFile, "1\n2\n3\n4\n", StandardCharsets.ISO_8859_1);
publisher.publish(writer);
File out = writer.getSourceFile(inputFile.scannerId());
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("1\n2\n3\n4\n");
}
@Test
public void publishTestSource() throws Exception {
FileUtils.write(sourceFile, "1\n2\n3\n4\n", StandardCharsets.ISO_8859_1);
// sampleFile.setQualifier(Qualifiers.UNIT_TEST_FILE);
publisher.publish(writer);
File out = writer.getSourceFile(inputFile.scannerId());
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("1\n2\n3\n4\n");
}
@Test
public void publishSourceWithLastLineNotEmpty() throws Exception {
FileUtils.write(sourceFile, "1\n2\n3\n4\n5", StandardCharsets.ISO_8859_1);
publisher.publish(writer);
File out = writer.getSourceFile(inputFile.scannerId());
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("1\n2\n3\n4\n5");
}
@Test
public void cleanLineEnds() throws Exception {
FileUtils.write(sourceFile, "\n2\r\n3\n4\r5", StandardCharsets.ISO_8859_1);
publisher.publish(writer);
File out = writer.getSourceFile(inputFile.scannerId());
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("\n2\n3\n4\n5");
}
}
| 4,508 | 35.362903 | 124 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/ContextPropertiesCacheTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.data.MapEntry.entry;
public class ContextPropertiesCacheTest {
ContextPropertiesCache underTest = new ContextPropertiesCache();
@Test
public void put_property() {
assertThat(underTest.getAll()).isEmpty();
underTest.put("foo", "bar");
assertThat(underTest.getAll()).containsOnly(entry("foo", "bar"));
}
@Test
public void put_overrides_existing_value() {
underTest.put("foo", "bar");
underTest.put("foo", "baz");
assertThat(underTest.getAll()).containsOnly(entry("foo", "baz"));
}
@Test
public void put_throws_IAE_if_key_is_null() {
assertThatThrownBy(() -> underTest.put(null, "bar"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Key of context property must not be null");
}
@Test
public void put_throws_IAE_if_value_is_null() {
assertThatThrownBy(() -> underTest.put("foo", null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value of context property must not be null");
}
}
| 2,055 | 32.704918 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/DefaultMetricsRepositoryLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.sonar.scanner.WsTestUtil;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
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.anyInt;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class DefaultMetricsRepositoryLoaderTest {
private static final String WS_URL = "/api/metrics/search?ps=500&p=";
private DefaultScannerWsClient wsClient;
private DefaultMetricsRepositoryLoader metricsRepositoryLoader;
@Before
public void setUp() throws IOException {
wsClient = mock(DefaultScannerWsClient.class);
WsTestUtil.mockReader(wsClient, WS_URL + "1", new StringReader(IOUtils.toString(this.getClass().getResourceAsStream("DefaultMetricsRepositoryLoaderTest/page1.json"))));
WsTestUtil.mockReader(wsClient, WS_URL + "2", new StringReader(IOUtils.toString(this.getClass().getResourceAsStream("DefaultMetricsRepositoryLoaderTest/page2.json"))));
metricsRepositoryLoader = new DefaultMetricsRepositoryLoader(wsClient);
}
@Test
public void test() {
MetricsRepository metricsRepository = metricsRepositoryLoader.load();
assertThat(metricsRepository.metrics()).hasSize(3);
WsTestUtil.verifyCall(wsClient, WS_URL + "1");
WsTestUtil.verifyCall(wsClient, WS_URL + "2");
verifyNoMoreInteractions(wsClient);
}
@Test
public void testIOError() throws IOException {
Reader reader = mock(Reader.class);
when(reader.read(any(char[].class), anyInt(), anyInt())).thenThrow(new IOException());
WsTestUtil.mockReader(wsClient, reader);
assertThatThrownBy(() -> metricsRepositoryLoader.load())
.isInstanceOf(IllegalStateException.class);
}
@Test
public void testCloseError() throws IOException {
Reader reader = mock(Reader.class);
when(reader.read(any(char[].class), anyInt(), anyInt())).thenReturn(-1);
doThrow(new IOException()).when(reader).close();
WsTestUtil.mockReader(wsClient, reader);
assertThatThrownBy(() -> metricsRepositoryLoader.load())
.isInstanceOf(IllegalStateException.class);
}
}
| 3,364 | 40.54321 | 172 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/DefaultNewCodePeriodLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import org.sonar.scanner.WsTestUtil;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonarqube.ws.NewCodePeriods;
import static org.mockito.Mockito.mock;
public class DefaultNewCodePeriodLoaderTest {
private DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class);
private DefaultNewCodePeriodLoader underTest = new DefaultNewCodePeriodLoader(wsClient);
@Test
public void loads_new_code_period() throws IOException {
prepareCallWithResults();
underTest.load("project", "branch");
verifyCalledPath("/api/new_code_periods/show.protobuf?project=project&branch=branch");
}
private void verifyCalledPath(String expectedPath) {
WsTestUtil.verifyCall(wsClient, expectedPath);
}
private void prepareCallWithResults() throws IOException {
WsTestUtil.mockStream(wsClient, createResponse(NewCodePeriods.NewCodePeriodType.REFERENCE_BRANCH, "main"));
}
private InputStream createResponse(NewCodePeriods.NewCodePeriodType type, String value) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
NewCodePeriods.ShowWSResponse response = NewCodePeriods.ShowWSResponse.newBuilder()
.setType(type)
.setValue(value)
.build();
response.writeTo(os);
return new ByteArrayInputStream(os.toByteArray());
}
}
| 2,364 | 35.384615 | 111 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/DefaultProjectRepositoriesLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository;
import com.google.common.io.Resources;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.WsTestUtil;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonarqube.ws.Batch.WsProjectResponse;
import org.sonarqube.ws.client.HttpException;
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.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DefaultProjectRepositoriesLoaderTest {
private final static String PROJECT_KEY = "foo?";
private DefaultProjectRepositoriesLoader loader;
private DefaultScannerWsClient wsClient;
@Before
public void prepare() throws IOException {
wsClient = mock(DefaultScannerWsClient.class);
InputStream is = mockData();
WsTestUtil.mockStream(wsClient, "/batch/project.protobuf?key=foo%3F", is);
loader = new DefaultProjectRepositoriesLoader(wsClient);
}
@Test
public void continueOnHttp404Exception() {
when(wsClient.call(any())).thenThrow(new HttpException("/batch/project.protobuf?key=foo%3F", HttpURLConnection.HTTP_NOT_FOUND, ""));
ProjectRepositories proj = loader.load(PROJECT_KEY, null);
assertThat(proj.exists()).isFalse();
}
@Test(expected = IllegalStateException.class)
public void failOnNonHttp404Exception() {
when(wsClient.call(any())).thenThrow(IllegalStateException.class);
ProjectRepositories proj = loader.load(PROJECT_KEY, null);
assertThat(proj.exists()).isFalse();
}
@Test(expected = IllegalStateException.class)
public void parsingError() throws IOException {
InputStream is = mock(InputStream.class);
when(is.read(any(byte[].class), anyInt(), anyInt())).thenThrow(IOException.class);
WsTestUtil.mockStream(wsClient, "/batch/project.protobuf?key=foo%3F", is);
loader.load(PROJECT_KEY, null);
}
@Test(expected = IllegalStateException.class)
public void failFastHttpError() {
HttpException http = new HttpException("url", 403, null);
IllegalStateException e = new IllegalStateException("http error", http);
WsTestUtil.mockException(wsClient, e);
loader.load(PROJECT_KEY, null);
}
@Test
public void failFastHttpErrorMessageException() {
HttpException http = new HttpException("uri", 403, null);
MessageException e = MessageException.of("http error", http);
WsTestUtil.mockException(wsClient, e);
assertThatThrownBy(() -> loader.load(PROJECT_KEY, null))
.isInstanceOf(MessageException.class)
.hasMessage("http error");
}
@Test
public void deserializeResponse() {
loader.load(PROJECT_KEY, null);
}
@Test
public void passAndEncodeProjectKeyParameter() {
loader.load(PROJECT_KEY, null);
WsTestUtil.verifyCall(wsClient, "/batch/project.protobuf?key=foo%3F");
}
private InputStream mockData() throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
WsProjectResponse.Builder projectResponseBuilder = WsProjectResponse.newBuilder();
WsProjectResponse response = projectResponseBuilder.build();
response.writeTo(os);
return new ByteArrayInputStream(os.toByteArray());
}
@Test
public void readRealResponse() throws IOException {
InputStream is = getTestResource("project.protobuf");
WsTestUtil.mockStream(wsClient, "/batch/project.protobuf?key=org.sonarsource.github%3Asonar-github-plugin", is);
DefaultInputFile file = mock(DefaultInputFile.class);
when(file.getModuleRelativePath()).thenReturn("src/test/java/org/sonar/plugins/github/PullRequestIssuePostJobTest.java");
ProjectRepositories proj = loader.load("org.sonarsource.github:sonar-github-plugin", null);
FileData fd = proj.fileData("org.sonarsource.github:sonar-github-plugin", file);
assertThat(fd.revision()).isEqualTo("27bf2c54633d05c5df402bbe09471fe43bd9e2e5");
assertThat(fd.hash()).isEqualTo("edb6b3b9ab92d8dc53ba90ab86cd422e");
}
private InputStream getTestResource(String name) throws IOException {
return Resources.asByteSource(this.getClass().getResource(this.getClass().getSimpleName() + "/" + name))
.openBufferedStream();
}
}
| 5,421 | 37.728571 | 136 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/DefaultQualityProfileLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.WsTestUtil;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonarqube.ws.Qualityprofiles;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
import org.sonarqube.ws.client.HttpException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
public class DefaultQualityProfileLoaderTest {
private final DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class);
private final DefaultQualityProfileLoader underTest = new DefaultQualityProfileLoader(wsClient);
@Test
public void load_gets_all_profiles_for_specified_project() throws IOException {
prepareCallWithResults();
underTest.load("foo");
verifyCalledPath("/api/qualityprofiles/search.protobuf?project=foo");
}
@Test
public void load_encodes_url_parameters() throws IOException {
WsTestUtil.mockStream(wsClient, "/api/qualityprofiles/search.protobuf?project=foo%232", createStreamOfProfiles("qp"));
underTest.load("foo#2");
verifyCalledPath("/api/qualityprofiles/search.protobuf?project=foo%232");
}
@Test
public void load_tries_default_if_no_profiles_found_for_project() throws IOException {
HttpException e = new HttpException("", 404, "{\"errors\":[{\"msg\":\"No project found with key 'foo'\"}]}");
WsTestUtil.mockException(wsClient, "/api/qualityprofiles/search.protobuf?project=foo", e);
WsTestUtil.mockStream(wsClient, "/api/qualityprofiles/search.protobuf?defaults=true", createStreamOfProfiles("qp"));
underTest.load("foo");
verifyCalledPath("/api/qualityprofiles/search.protobuf?project=foo");
verifyCalledPath("/api/qualityprofiles/search.protobuf?defaults=true");
}
@Test
public void load_throws_MessageException_if_no_profiles_are_available_for_specified_project() throws IOException {
prepareCallWithEmptyResults();
assertThatThrownBy(() -> underTest.load("project"))
.isInstanceOf(MessageException.class)
.hasMessageContaining("No quality profiles");
}
private void verifyCalledPath(String expectedPath) {
WsTestUtil.verifyCall(wsClient, expectedPath);
}
private void prepareCallWithResults() throws IOException {
WsTestUtil.mockStream(wsClient, createStreamOfProfiles("qp"));
}
private void prepareCallWithEmptyResults() throws IOException {
WsTestUtil.mockStream(wsClient, createStreamOfProfiles());
}
private static InputStream createStreamOfProfiles(String... names) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
Qualityprofiles.SearchWsResponse.Builder responseBuilder = Qualityprofiles.SearchWsResponse.newBuilder();
for (String n : names) {
QualityProfile qp = QualityProfile.newBuilder().setKey(n).setName(n).setLanguage("lang").build();
responseBuilder.addProfiles(qp);
}
responseBuilder.build().writeTo(os);
return new ByteArrayInputStream(os.toByteArray());
}
}
| 4,062 | 38.833333 | 122 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/MultiModuleProjectRepositoryTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository;
import java.util.Map;
import org.assertj.core.util.Maps;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
public class MultiModuleProjectRepositoryTest {
private MultiModuleProjectRepository repository;
@Before
public void setUp() {
SingleProjectRepository repository1 = new SingleProjectRepository(Maps.newHashMap("/Abc.java", new FileData("123", "456")));
SingleProjectRepository repository2 = new SingleProjectRepository(Maps.newHashMap("/Def.java", new FileData("567", "321")));
Map<String, SingleProjectRepository> moduleRepositories = Maps.newHashMap("module1", repository1);
moduleRepositories.put("module2", repository2);
repository = new MultiModuleProjectRepository(moduleRepositories);
}
@Test
public void test_file_data_when_module_and_file_exist() {
FileData fileData = repository.fileData("module2", "/Def.java");
assertNotNull(fileData);
assertThat(fileData.hash()).isEqualTo("567");
assertThat(fileData.revision()).isEqualTo("321");
}
@Test
public void test_file_data_when_module_does_not_exist() {
FileData fileData = repository.fileData("unknown", "/Def.java");
assertThat(fileData).isNull();
}
}
| 2,173 | 35.233333 | 128 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/ProjectRepositoriesProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class ProjectRepositoriesProviderTest {
private ProjectRepositoriesProvider underTest;
private ProjectRepositories project;
private final ProjectRepositoriesLoader loader = mock(ProjectRepositoriesLoader.class);
private final ScannerProperties props = mock(ScannerProperties.class);
private final BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
@Before
public void setUp() {
underTest = new ProjectRepositoriesProvider(loader, props, branchConfiguration);
Map<String, FileData> fileMap = emptyMap();
project = new SingleProjectRepository(fileMap);
when(props.getProjectKey()).thenReturn("key");
}
@Test
public void testValidation() {
when(loader.load(eq("key"), any())).thenReturn(project);
assertThat(underTest.projectRepositories()).isEqualTo(project);
}
@Test
public void testAssociated() {
when(loader.load(eq("key"), any())).thenReturn(project);
ProjectRepositories repo = underTest.projectRepositories();
assertThat(repo.exists()).isTrue();
verify(props).getProjectKey();
verify(loader).load("key", null);
verifyNoMoreInteractions(loader, props);
}
}
| 2,620 | 35.915493 | 90 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/QualityProfileProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.rule.QualityProfiles;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class QualityProfileProviderTest {
@Rule
public LogTester logTester = new LogTester();
private QualityProfilesProvider qualityProfileProvider;
private QualityProfileLoader loader = mock(QualityProfileLoader.class);
private ScannerProperties props = mock(ScannerProperties.class);
private List<QualityProfile> response;
@Before
public void setUp() {
qualityProfileProvider = new QualityProfilesProvider();
when(props.getProjectKey()).thenReturn("project");
response = new ArrayList<>(1);
response.add(QualityProfile.newBuilder().setKey("profile").setName("profile").setLanguage("lang").setRulesUpdatedAt(DateUtils.formatDateTime(new Date())).build());
}
@Test
public void testProvide() {
when(loader.load("project")).thenReturn(response);
QualityProfiles qps = qualityProfileProvider.provide(loader, props);
assertResponse(qps);
verify(loader).load("project");
verifyNoMoreInteractions(loader);
}
@Test
public void testProfileProp() {
when(loader.load("project")).thenReturn(response);
QualityProfiles qps = qualityProfileProvider.provide(loader, props);
assertResponse(qps);
verify(loader).load("project");
verifyNoMoreInteractions(loader);
}
private void assertResponse(QualityProfiles qps) {
assertThat(qps.findAll()).extracting("key").containsExactly("profile");
}
}
| 2,915 | 32.136364 | 167 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/ReferenceBranchSupplierTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.config.Configuration;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.branch.BranchType;
import org.sonar.scanner.scan.branch.ProjectBranches;
import org.sonarqube.ws.NewCodePeriods;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class ReferenceBranchSupplierTest {
private final static String PROJECT_KEY = "project";
private final static String BRANCH_KEY = "branch";
private final static Path BASE_DIR = Paths.get("root");
private final NewCodePeriodLoader newCodePeriodLoader = mock(NewCodePeriodLoader.class);
private final BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
private final Configuration configuration = mock(Configuration.class);
private final DefaultInputProject project = mock(DefaultInputProject.class);
private final ProjectBranches projectBranches = mock(ProjectBranches.class);
private final ReferenceBranchSupplier referenceBranchSupplier = new ReferenceBranchSupplier(configuration, newCodePeriodLoader, branchConfiguration, project, projectBranches);
@Before
public void setUp() {
when(projectBranches.isEmpty()).thenReturn(false);
when(project.key()).thenReturn(PROJECT_KEY);
when(project.getBaseDir()).thenReturn(BASE_DIR);
when(configuration.get("sonar.newCode.referenceBranch")).thenReturn(Optional.empty());
}
@Test
public void get_returns_reference_branch_when_set() {
when(branchConfiguration.branchType()).thenReturn(BranchType.BRANCH);
when(branchConfiguration.branchName()).thenReturn(BRANCH_KEY);
when(newCodePeriodLoader.load(PROJECT_KEY, BRANCH_KEY)).thenReturn(createResponse(NewCodePeriods.NewCodePeriodType.REFERENCE_BRANCH, "main"));
assertThat(referenceBranchSupplier.get()).isEqualTo("main");
}
@Test
public void get_uses_scanner_property_with_higher_priority() {
when(branchConfiguration.branchType()).thenReturn(BranchType.BRANCH);
when(branchConfiguration.branchName()).thenReturn(BRANCH_KEY);
when(newCodePeriodLoader.load(PROJECT_KEY, BRANCH_KEY)).thenReturn(createResponse(NewCodePeriods.NewCodePeriodType.REFERENCE_BRANCH, "main"));
when(configuration.get("sonar.newCode.referenceBranch")).thenReturn(Optional.of("master2"));
assertThat(referenceBranchSupplier.get()).isEqualTo("master2");
}
@Test
public void getFromProperties_uses_scanner_property() {
when(branchConfiguration.branchType()).thenReturn(BranchType.BRANCH);
when(branchConfiguration.branchName()).thenReturn(BRANCH_KEY);
when(configuration.get("sonar.newCode.referenceBranch")).thenReturn(Optional.of("master2"));
assertThat(referenceBranchSupplier.getFromProperties()).isEqualTo("master2");
}
@Test
public void getFromProperties_returns_null_if_no_property() {
assertThat(referenceBranchSupplier.getFromProperties()).isNull();
}
@Test
public void getFromProperties_throws_ISE_if_reference_is_the_same_as_branch() {
when(branchConfiguration.branchType()).thenReturn(BranchType.BRANCH);
when(branchConfiguration.branchName()).thenReturn(BRANCH_KEY);
when(configuration.get("sonar.newCode.referenceBranch")).thenReturn(Optional.of(BRANCH_KEY));
assertThatThrownBy(referenceBranchSupplier::getFromProperties).isInstanceOf(IllegalStateException.class);
}
@Test
public void get_uses_default_branch_if_no_branch_specified() {
when(branchConfiguration.branchType()).thenReturn(BranchType.BRANCH);
when(branchConfiguration.branchName()).thenReturn(null);
when(projectBranches.defaultBranchName()).thenReturn("default");
when(newCodePeriodLoader.load(PROJECT_KEY, "default")).thenReturn(createResponse(NewCodePeriods.NewCodePeriodType.REFERENCE_BRANCH, "main"));
assertThat(referenceBranchSupplier.get()).isEqualTo("main");
}
@Test
public void get_returns_null_if_no_branches() {
when(projectBranches.isEmpty()).thenReturn(true);
assertThat(referenceBranchSupplier.get()).isNull();
verify(branchConfiguration).isPullRequest();
verify(projectBranches).isEmpty();
verifyNoMoreInteractions(branchConfiguration);
verifyNoInteractions(newCodePeriodLoader);
}
@Test
public void get_returns_null_if_reference_branch_is_the_branch_being_analyzed() {
when(branchConfiguration.branchType()).thenReturn(BranchType.BRANCH);
when(branchConfiguration.branchName()).thenReturn(BRANCH_KEY);
when(newCodePeriodLoader.load(PROJECT_KEY, BRANCH_KEY)).thenReturn(createResponse(NewCodePeriods.NewCodePeriodType.REFERENCE_BRANCH, BRANCH_KEY));
assertThat(referenceBranchSupplier.get()).isNull();
verify(branchConfiguration, times(2)).branchName();
verify(branchConfiguration, times(2)).isPullRequest();
verify(newCodePeriodLoader).load(PROJECT_KEY, BRANCH_KEY);
verifyNoMoreInteractions(branchConfiguration);
}
@Test
public void get_returns_null_if_pull_request() {
when(branchConfiguration.isPullRequest()).thenReturn(true);
assertThat(referenceBranchSupplier.get()).isNull();
verify(branchConfiguration).isPullRequest();
verifyNoInteractions(newCodePeriodLoader);
verifyNoMoreInteractions(branchConfiguration);
}
@Test
public void get_returns_null_if_new_code_period_is_not_ref() {
when(branchConfiguration.isPullRequest()).thenReturn(true);
when(branchConfiguration.branchName()).thenReturn(BRANCH_KEY);
when(newCodePeriodLoader.load(PROJECT_KEY, BRANCH_KEY)).thenReturn(createResponse(NewCodePeriods.NewCodePeriodType.NUMBER_OF_DAYS, "2"));
assertThat(referenceBranchSupplier.get()).isNull();
}
private NewCodePeriods.ShowWSResponse createResponse(NewCodePeriods.NewCodePeriodType type, String value) {
return NewCodePeriods.ShowWSResponse.newBuilder()
.setType(type)
.setValue(value)
.build();
}
}
| 7,252 | 41.91716 | 177 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/SingleProjectRepositoryTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository;
import org.junit.Before;
import org.junit.Test;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
public class SingleProjectRepositoryTest {
private SingleProjectRepository repository;
@Before
public void setUp() {
repository = new SingleProjectRepository(singletonMap("/Abc.java", new FileData("123", "456")));
}
@Test
public void test_file_data_when_file_exists() {
FileData fileData = repository.fileData("/Abc.java");
assertNotNull(fileData);
assertThat(fileData.hash()).isEqualTo("123");
assertThat(fileData.revision()).isEqualTo("456");
}
@Test
public void test_file_data_when_file_does_not_exist() {
FileData fileData = repository.fileData("/Def.java");
assertThat(fileData).isNull();
}
}
| 1,738 | 31.203704 | 100 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/language/DefaultLanguagesRepositoryTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository.language;
import org.junit.Test;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DefaultLanguagesRepositoryTest {
private final Languages languages = mock(Languages.class);
private final DefaultLanguagesRepository underTest = new DefaultLanguagesRepository(languages);
@Test
public void returns_all_languages() {
when(languages.all()).thenReturn(new Language[] {new TestLanguage("k1", true), new TestLanguage("k2", false)});
assertThat(underTest.all())
.extracting("key", "name", "fileSuffixes", "publishAllFiles")
.containsOnly(
tuple("k1", "name k1", new String[] {"k1"}, true),
tuple("k2", "name k2", new String[] {"k2"}, false)
);
}
@Test
public void publishAllFiles_by_default() {
when(languages.all()).thenReturn(new Language[] {new TestLanguage2("k1"), new TestLanguage2("k2")});
assertThat(underTest.all())
.extracting("key", "name", "fileSuffixes", "publishAllFiles")
.containsOnly(
tuple("k1", "name k1", new String[] {"k1"}, true),
tuple("k2", "name k2", new String[] {"k2"}, true)
);
}
@Test
public void get_find_language_by_key() {
when(languages.get("k1")).thenReturn(new TestLanguage2("k1"));
assertThat(underTest.get("k1"))
.extracting("key", "name", "fileSuffixes", "publishAllFiles")
.containsOnly("k1", "name k1", new String[] {"k1"}, true);
}
private static class TestLanguage implements Language {
private final String key;
private final boolean publishAllFiles;
public TestLanguage(String key, boolean publishAllFiles) {
this.key = key;
this.publishAllFiles = publishAllFiles;
}
@Override
public String getKey() {
return key;
}
@Override
public String getName() {
return "name " + key;
}
@Override
public String[] getFileSuffixes() {
return new String[] {key};
}
@Override
public boolean publishAllFiles() {
return publishAllFiles;
}
}
private static class TestLanguage2 implements Language {
private final String key;
public TestLanguage2(String key) {
this.key = key;
}
@Override
public String getKey() {
return key;
}
@Override
public String getName() {
return "name " + key;
}
@Override
public String[] getFileSuffixes() {
return new String[] {key};
}
}
}
| 3,525 | 28.630252 | 115 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/language/LanguageTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository.language;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class LanguageTest {
@Test
public void hashCode_and_equals_depends_on_key() {
Language lang1 = new Language(mockApiLanguage("key1", "name1", true, new String[] {"f1"}, new String[0]));
Language lang2 = new Language(mockApiLanguage("key1", "name2", false, new String[] {"f2"}, new String[0]));
Language lang3 = new Language(mockApiLanguage("key2", "name1", true, new String[] {"f1"}, new String[0]));
assertThat(lang1)
.hasSameHashCodeAs(lang2)
.doesNotHaveSameHashCodeAs(lang3);
assertThat(lang2).doesNotHaveSameHashCodeAs(lang3);
assertThat(lang1)
.isEqualTo(lang2)
.isNotEqualTo(lang3);
assertThat(lang2).isNotEqualTo(lang3);
}
@Test
public void getters_match_constructor() {
Language lang1 = new Language(mockApiLanguage("key1", "name1", true, new String[] {"f1"}, new String[] {"p1"}));
assertThat(lang1.key()).isEqualTo("key1");
assertThat(lang1.name()).isEqualTo("name1");
assertThat(lang1.isPublishAllFiles()).isTrue();
assertThat(lang1.fileSuffixes()).containsOnly("f1");
assertThat(lang1.filenamePatterns()).containsOnly("p1");
}
private org.sonar.api.resources.Language mockApiLanguage(String key, String name, boolean publishAllFiles, String[] fileSuffixes, String[] filenamePatterns) {
org.sonar.api.resources.Language mock = mock(org.sonar.api.resources.Language.class);
when(mock.getKey()).thenReturn(key);
when(mock.getName()).thenReturn(name);
when(mock.publishAllFiles()).thenReturn(publishAllFiles);
when(mock.getFileSuffixes()).thenReturn(fileSuffixes);
when(mock.filenamePatterns()).thenReturn(filenamePatterns);
return mock;
}
}
| 2,734 | 41.076923 | 160 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/settings/AbstractSettingsLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository.settings;
import java.util.List;
import org.junit.Test;
import org.sonarqube.ws.Settings.FieldValues;
import org.sonarqube.ws.Settings.FieldValues.Value;
import org.sonarqube.ws.Settings.FieldValues.Value.Builder;
import org.sonarqube.ws.Settings.Setting;
import org.sonarqube.ws.Settings.Values;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
public class AbstractSettingsLoaderTest {
@Test
public void should_load_global_multivalue_settings() {
assertThat(AbstractSettingsLoader.toMap(singletonList(Setting.newBuilder()
.setKey("sonar.preview.supportedPlugins")
.setValues(Values.newBuilder().addValues("java").addValues("php")).build())))
.containsExactly(entry("sonar.preview.supportedPlugins", "java,php"));
}
@Test
public void should_escape_global_multivalue_settings() {
assertThat(AbstractSettingsLoader.toMap(singletonList(Setting.newBuilder()
.setKey("sonar.preview.supportedPlugins")
.setValues(Values.newBuilder().addValues("ja,va").addValues("p\"hp")).build())))
.containsExactly(entry("sonar.preview.supportedPlugins", "\"ja,va\",\"p\"\"hp\""));
}
@Test
public void should_throw_exception_when_no_value_of_non_secured_settings() {
Setting setting = Setting.newBuilder().setKey("sonar.open.setting").build();
List<Setting> singletonList = singletonList(setting);
assertThatThrownBy(() -> AbstractSettingsLoader.toMap(singletonList))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Unknown property value for sonar.open.setting");
}
@Test
public void should_filter_secured_settings_without_value() {
assertThat(AbstractSettingsLoader.toMap(singletonList(Setting.newBuilder()
.setKey("sonar.setting.secured").build())))
.isEmpty();
}
@Test
public void should_load_global_propertyset_settings() {
Builder valuesBuilder = Value.newBuilder();
valuesBuilder.putValue("filepattern", "**/*.xml");
valuesBuilder.putValue("rulepattern", "*:S12345");
Value value1 = valuesBuilder.build();
valuesBuilder.clear();
valuesBuilder.putValue("filepattern", "**/*.java");
valuesBuilder.putValue("rulepattern", "*:S456");
Value value2 = valuesBuilder.build();
assertThat(AbstractSettingsLoader.toMap(singletonList(Setting.newBuilder()
.setKey("sonar.issue.exclusions.multicriteria")
.setFieldValues(FieldValues.newBuilder().addFieldValues(value1).addFieldValues(value2)).build())))
.containsOnly(entry("sonar.issue.exclusions.multicriteria", "1,2"),
entry("sonar.issue.exclusions.multicriteria.1.filepattern", "**/*.xml"),
entry("sonar.issue.exclusions.multicriteria.1.rulepattern", "*:S12345"),
entry("sonar.issue.exclusions.multicriteria.2.filepattern", "**/*.java"),
entry("sonar.issue.exclusions.multicriteria.2.rulepattern", "*:S456"));
}
}
| 3,953 | 41.516129 | 104 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/settings/DefaultGlobalSettingsLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository.settings;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Map;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonarqube.ws.Settings;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.WsResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class DefaultGlobalSettingsLoaderTest {
private DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class);
private DefaultGlobalSettingsLoader underTest = new DefaultGlobalSettingsLoader(wsClient);
@Test
public void loadGlobalSettings() throws IOException {
WsResponse response = mock(WsResponse.class);
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
Settings.ValuesWsResponse.newBuilder()
.addSettings(Settings.Setting.newBuilder()
.setKey("abc").setValue("def")
.build())
.addSettings(Settings.Setting.newBuilder()
.setKey("123").setValue("456")
.build())
.build()
.writeTo(out);
out.close();
when(response.contentStream()).thenReturn(in);
when(wsClient.call(any())).thenReturn(response);
Map<String, String> result = underTest.loadGlobalSettings();
ArgumentCaptor<GetRequest> argumentCaptor = ArgumentCaptor.forClass(GetRequest.class);
verify(wsClient, times(1)).call(argumentCaptor.capture());
assertThat(argumentCaptor.getValue().getPath()).isEqualTo("api/settings/values.protobuf");
assertThat(result)
.isNotNull()
.hasSize(2)
.containsEntry("abc", "def")
.containsEntry("123", "456");
}
}
| 2,823 | 36.653333 | 94 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/repository/settings/DefaultProjectSettingsLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.repository.settings;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Map;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonarqube.ws.Settings;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.WsResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class DefaultProjectSettingsLoaderTest {
private DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class);
private ScannerProperties properties = mock(ScannerProperties.class);
private DefaultProjectSettingsLoader underTest = new DefaultProjectSettingsLoader(wsClient, properties);
@Test
public void loadProjectSettings() throws IOException {
WsResponse response = mock(WsResponse.class);
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
Settings.ValuesWsResponse.newBuilder()
.addSettings(Settings.Setting.newBuilder()
.setKey("abc").setValue("def")
.build())
.addSettings(Settings.Setting.newBuilder()
.setKey("123").setValue("456")
.build())
.build()
.writeTo(out);
out.close();
when(response.contentStream()).thenReturn(in);
when(wsClient.call(any())).thenReturn(response);
when(properties.getProjectKey()).thenReturn("project_key");
Map<String, String> result = underTest.loadProjectSettings();
ArgumentCaptor<GetRequest> argumentCaptor = ArgumentCaptor.forClass(GetRequest.class);
verify(wsClient, times(1)).call(argumentCaptor.capture());
assertThat(argumentCaptor.getValue().getPath()).isEqualTo("api/settings/values.protobuf?component=project_key");
assertThat(result)
.isNotNull()
.hasSize(2)
.containsEntry("abc", "def")
.containsEntry("123", "456");
}
}
| 3,052 | 38.141026 | 116 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/ActiveRulesBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.rule;
import org.junit.Test;
import org.sonar.api.batch.rule.ActiveRule;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.batch.rule.internal.NewActiveRule;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ActiveRulesBuilderTest {
@Test
public void no_rules() {
ActiveRulesBuilder builder = new ActiveRulesBuilder();
ActiveRules rules = builder.build();
assertThat(rules.findAll()).isEmpty();
}
@Test
public void build_rules() {
NewActiveRule activeRule = new NewActiveRule.Builder()
.setRuleKey(RuleKey.of("java", "S0001"))
.setName("My Rule")
.setSeverity(Severity.CRITICAL)
.setInternalKey("__S0001__")
.setParam("min", "20")
.build();
ActiveRules activeRules = new ActiveRulesBuilder()
.addRule(activeRule)
// most simple rule
.addRule(new NewActiveRule.Builder().setRuleKey(RuleKey.of("java", "S0002")).build())
.addRule(new NewActiveRule.Builder()
.setRuleKey(RuleKey.of("findbugs", "NPE"))
.setInternalKey(null)
.setSeverity(null)
.setParam("foo", null)
.build())
.build();
assertThat(activeRules.findAll()).hasSize(3);
assertThat(activeRules.findByRepository("java")).hasSize(2);
assertThat(activeRules.findByRepository("findbugs")).hasSize(1);
assertThat(activeRules.findByInternalKey("java", "__S0001__")).isNotNull();
assertThat(activeRules.findByRepository("unknown")).isEmpty();
ActiveRule java1 = activeRules.find(RuleKey.of("java", "S0001"));
assertThat(java1.ruleKey().repository()).isEqualTo("java");
assertThat(java1.ruleKey().rule()).isEqualTo("S0001");
assertThat(java1.severity()).isEqualTo(Severity.CRITICAL);
assertThat(java1.internalKey()).isEqualTo("__S0001__");
assertThat(java1.params()).hasSize(1);
assertThat(java1.param("min")).isEqualTo("20");
ActiveRule java2 = activeRules.find(RuleKey.of("java", "S0002"));
assertThat(java2.ruleKey().repository()).isEqualTo("java");
assertThat(java2.ruleKey().rule()).isEqualTo("S0002");
assertThat(java2.severity()).isEqualTo(Severity.defaultSeverity());
assertThat(java2.params()).isEmpty();
ActiveRule findbugsRule = activeRules.find(RuleKey.of("findbugs", "NPE"));
assertThat(findbugsRule.severity()).isEqualTo(Severity.defaultSeverity());
assertThat(findbugsRule.internalKey()).isNull();
assertThat(findbugsRule.params()).isEmpty();
}
@Test
public void fail_to_add_twice_the_same_rule() {
ActiveRulesBuilder builder = new ActiveRulesBuilder();
NewActiveRule rule = new NewActiveRule.Builder()
.setRuleKey(RuleKey.of("java", "S0001"))
.build();
builder.addRule(rule);
assertThatThrownBy(() -> builder.addRule(rule))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Rule 'java:S0001' is already activated");
}
}
| 3,976 | 37.61165 | 91 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/ActiveRulesProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.rule;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.assertj.core.groups.Tuple;
import org.junit.Test;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.rule.LoadedActiveRule;
import org.sonar.api.batch.rule.internal.DefaultActiveRules;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.DateUtils;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class ActiveRulesProviderTest {
private final ActiveRulesProvider provider = new ActiveRulesProvider();
private final DefaultActiveRulesLoader loader = mock(DefaultActiveRulesLoader.class);
@Test
public void testCombinationOfRules() {
LoadedActiveRule r1 = mockRule("rule1");
LoadedActiveRule r2 = mockRule("rule2");
LoadedActiveRule r3 = mockRule("rule3");
List<LoadedActiveRule> qp1Rules = ImmutableList.of(r1, r2);
List<LoadedActiveRule> qp2Rules = ImmutableList.of(r2, r3);
List<LoadedActiveRule> qp3Rules = ImmutableList.of(r1, r3);
when(loader.load("qp1")).thenReturn(qp1Rules);
when(loader.load("qp2")).thenReturn(qp2Rules);
when(loader.load("qp3")).thenReturn(qp3Rules);
QualityProfiles profiles = mockProfiles("qp1", "qp2", "qp3");
DefaultActiveRules activeRules = provider.provide(loader, profiles);
assertThat(activeRules.findAll()).hasSize(3);
assertThat(activeRules.findAll()).extracting("ruleKey").containsOnly(
RuleKey.of("rule1", "rule1"), RuleKey.of("rule2", "rule2"), RuleKey.of("rule3", "rule3"));
verify(loader).load("qp1");
verify(loader).load("qp2");
verify(loader).load("qp3");
assertThat(activeRules.getDeprecatedRuleKeys(RuleKey.of("rule1", "rule1"))).containsOnly("rule1old:rule1old");
verifyNoMoreInteractions(loader);
}
@Test
public void testParamsAreTransformed() {
LoadedActiveRule r1 = mockRule("rule1");
LoadedActiveRule r2 = mockRule("rule2");
r2.setParams(ImmutableMap.of("foo1", "bar1", "foo2", "bar2"));
List<LoadedActiveRule> qpRules = ImmutableList.of(r1, r2);
when(loader.load("qp")).thenReturn(qpRules);
QualityProfiles profiles = mockProfiles("qp");
ActiveRules activeRules = provider.provide(loader, profiles);
assertThat(activeRules.findAll()).hasSize(2);
assertThat(activeRules.findAll()).extracting("ruleKey", "params").containsOnly(
Tuple.tuple(RuleKey.of("rule1", "rule1"), ImmutableMap.of()),
Tuple.tuple(RuleKey.of("rule2", "rule2"), ImmutableMap.of("foo1", "bar1", "foo2", "bar2")));
verify(loader).load("qp");
verifyNoMoreInteractions(loader);
}
private static QualityProfiles mockProfiles(String... keys) {
List<QualityProfile> profiles = new LinkedList<>();
for (String k : keys) {
QualityProfile p = QualityProfile.newBuilder().setKey(k).setLanguage(k).setRulesUpdatedAt(DateUtils.formatDateTime(new Date())).build();
profiles.add(p);
}
return new QualityProfiles(profiles);
}
private static LoadedActiveRule mockRule(String name) {
LoadedActiveRule r = new LoadedActiveRule();
r.setName(name);
r.setRuleKey(RuleKey.of(name, name));
r.setDeprecatedKeys(ImmutableSet.of(RuleKey.of(name + "old", name + "old")));
return r;
}
}
| 4,506 | 37.853448 | 142 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/DefaultActiveRulesLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.rule;
import com.google.common.collect.ImmutableSortedMap;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.rule.LoadedActiveRule;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.WsTestUtil;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonarqube.ws.Rules;
import org.sonarqube.ws.Rules.Active;
import org.sonarqube.ws.Rules.ActiveList;
import org.sonarqube.ws.Rules.Actives;
import org.sonarqube.ws.Rules.Rule;
import org.sonarqube.ws.Rules.SearchResponse;
import org.sonarqube.ws.Rules.SearchResponse.Builder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class DefaultActiveRulesLoaderTest {
private static final int PAGE_SIZE_1 = 150;
private static final int PAGE_SIZE_2 = 76;
private static final RuleKey EXAMPLE_KEY = RuleKey.of("java", "S108");
private static final String FORMAT_KEY = "format";
private static final String FORMAT_VALUE = "^[a-z][a-zA-Z0-9]*$";
private static final String SEVERITY_VALUE = Severity.MINOR;
private DefaultActiveRulesLoader loader;
private DefaultScannerWsClient wsClient;
@Before
public void setUp() {
wsClient = mock(DefaultScannerWsClient.class);
BranchConfiguration branchConfig = mock(BranchConfiguration.class);
when(branchConfig.isPullRequest()).thenReturn(false);
loader = new DefaultActiveRulesLoader(wsClient);
}
@Test
public void feed_real_response_encode_qp() {
int total = PAGE_SIZE_1 + PAGE_SIZE_2;
WsTestUtil.mockStream(wsClient, urlOfPage(1), responseOfSize(PAGE_SIZE_1, total));
WsTestUtil.mockStream(wsClient, urlOfPage(2), responseOfSize(PAGE_SIZE_2, total));
Collection<LoadedActiveRule> activeRules = loader.load("c+-test_c+-values-17445");
assertThat(activeRules).hasSize(total);
assertThat(activeRules)
.filteredOn(r -> r.getRuleKey().equals(EXAMPLE_KEY))
.extracting(LoadedActiveRule::getParams)
.extracting(p -> p.get(FORMAT_KEY))
.containsExactly(FORMAT_VALUE);
assertThat(activeRules)
.filteredOn(r -> r.getRuleKey().equals(EXAMPLE_KEY))
.extracting(LoadedActiveRule::getSeverity)
.containsExactly(SEVERITY_VALUE);
WsTestUtil.verifyCall(wsClient, urlOfPage(1));
WsTestUtil.verifyCall(wsClient, urlOfPage(2));
verifyNoMoreInteractions(wsClient);
}
@Test
public void exception_thrown_when_elasticsearch_index_inconsistent() {
WsTestUtil.mockStream(wsClient, urlOfPage(1), prepareCorruptedResponse());
assertThatThrownBy(() -> loader.load("c+-test_c+-values-17445"))
.isInstanceOf(MessageException.class)
.hasMessage("Elasticsearch indices have become inconsistent. Consider re-indexing. " +
"Check documentation for more information https://docs.sonarqube.org/latest/setup/troubleshooting");
}
private String urlOfPage(int page) {
return "/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt,updatedAt,deprecatedKeys&activation=true"
+ ("") + "&qprofile=c%2B-test_c%2B-values-17445&ps=500&p=" + page + "";
}
/**
* Generates an imaginary protobuf result.
*
* @param numberOfRules the number of rules, that the response should contain
* @param total the number of results on all pages
* @return the binary stream
*/
private InputStream responseOfSize(int numberOfRules, int total) {
Builder rules = SearchResponse.newBuilder();
Actives.Builder actives = Actives.newBuilder();
IntStream.rangeClosed(1, numberOfRules)
.mapToObj(i -> RuleKey.of("java", "S" + i))
.forEach(key -> {
Rule.Builder ruleBuilder = Rule.newBuilder();
ruleBuilder.setKey(key.toString());
rules.addRules(ruleBuilder);
Active.Builder activeBuilder = Active.newBuilder();
activeBuilder.setCreatedAt("2014-05-27T15:50:45+0100");
activeBuilder.setUpdatedAt("2014-05-27T15:50:45+0100");
if (EXAMPLE_KEY.equals(key)) {
activeBuilder.addParams(Rules.Active.Param.newBuilder().setKey(FORMAT_KEY).setValue(FORMAT_VALUE));
activeBuilder.setSeverity(SEVERITY_VALUE);
}
ActiveList activeList = Rules.ActiveList.newBuilder().addActiveList(activeBuilder).build();
actives.putAllActives(ImmutableSortedMap.of(key.toString(), activeList));
});
rules.setActives(actives);
rules.setPs(numberOfRules);
rules.setTotal(total);
return new ByteArrayInputStream(rules.build().toByteArray());
}
private InputStream prepareCorruptedResponse() {
Builder rules = SearchResponse.newBuilder();
Actives.Builder actives = Actives.newBuilder();
IntStream.rangeClosed(1, 3)
.mapToObj(i -> RuleKey.of("java", "S" + i))
.forEach(key -> {
Rule.Builder ruleBuilder = Rule.newBuilder();
ruleBuilder.setKey(key.toString());
rules.addRules(ruleBuilder);
});
rules.setActives(actives);
rules.setPs(3);
rules.setTotal(3);
return new ByteArrayInputStream(rules.build().toByteArray());
}
}
| 6,392 | 37.981707 | 155 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/DefaultRulesLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.rule;
import com.google.common.io.ByteSource;
import com.google.common.io.Resources;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.junit.Test;
import org.sonar.scanner.WsTestUtil;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonarqube.ws.Rules.ListResponse.Rule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
public class DefaultRulesLoaderTest {
@Test
public void testParseServerResponse() throws IOException {
DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class);
InputStream is = Resources.asByteSource(this.getClass().getResource("DefaultRulesLoaderTest/response.protobuf")).openBufferedStream();
WsTestUtil.mockStream(wsClient, is);
DefaultRulesLoader loader = new DefaultRulesLoader(wsClient);
List<Rule> ruleList = loader.load();
assertThat(ruleList).hasSize(318);
}
@Test
public void testError() throws IOException {
DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class);
InputStream is = ByteSource.wrap("trash".getBytes()).openBufferedStream();
WsTestUtil.mockStream(wsClient, is);
DefaultRulesLoader loader = new DefaultRulesLoader(wsClient);
assertThatThrownBy(() -> loader.load())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Unable to get rules");
}
}
| 2,338 | 37.983333 | 138 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/QProfileTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class QProfileTest {
@Test
public void testEquals() {
QProfile q1 = new QProfile("k1", "name1", null, null);
QProfile q2 = new QProfile("k1", "name2", null, null);
QProfile q3 = new QProfile("k3", "name3", null, null);
assertThat(q1)
.isEqualTo(q2)
.isNotEqualTo(q3)
.isNotNull()
.isNotEqualTo("str");
assertThat(q2).isNotEqualTo(q3);
assertThat(q1).hasSameHashCodeAs(q2);
assertThat(q1.hashCode()).isNotEqualTo(q3.hashCode());
assertThat(q2.hashCode()).isNotEqualTo(q3.hashCode());
}
}
| 1,517 | 32.733333 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/QProfileVerifierTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.rule;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class QProfileVerifierTest {
private InputComponentStore store;
private QualityProfiles profiles;
@Before
public void before() {
store = new InputComponentStore(mock(BranchConfiguration.class), mock(SonarRuntime.class));
profiles = mock(QualityProfiles.class);
QProfile javaProfile = new QProfile("p1", "My Java profile", "java", null);
when(profiles.findByLanguage("java")).thenReturn(javaProfile);
QProfile cobolProfile = new QProfile("p2", "My Cobol profile", "cobol", null);
when(profiles.findByLanguage("cobol")).thenReturn(cobolProfile);
}
@Test
public void should_log_all_used_profiles() {
store.put("foo", new TestInputFileBuilder("foo", "src/Bar.java").setLanguage("java").build());
store.put("foo", new TestInputFileBuilder("foo", "src/Baz.cbl").setLanguage("cobol").build());
QProfileVerifier profileLogger = new QProfileVerifier(store, profiles);
Logger logger = mock(Logger.class);
profileLogger.execute(logger);
verify(logger).info("Quality profile for {}: {}", "java", "My Java profile");
verify(logger).info("Quality profile for {}: {}", "cobol", "My Cobol profile");
}
@Test
public void should_not_fail_if_no_language_on_project() {
QProfileVerifier profileLogger = new QProfileVerifier(store, profiles);
profileLogger.execute();
}
@Test
public void should_not_fail_if_default_profile_used_at_least_once() {
store.put("foo", new TestInputFileBuilder("foo", "src/Bar.java").setLanguage("java").build());
QProfileVerifier profileLogger = new QProfileVerifier(store, profiles);
profileLogger.execute();
}
}
| 2,928 | 36.075949 | 98 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/rule/RulesProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.rule;
import com.google.common.collect.Lists;
import org.junit.Test;
import org.sonar.api.batch.rule.Rules;
import org.sonarqube.ws.Rules.ListResponse.Rule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RulesProviderTest {
@Test
public void testRuleTranslation() {
RulesLoader loader = mock(RulesLoader.class);
when(loader.load()).thenReturn(Lists.newArrayList(getTestRule()));
RulesProvider provider = new RulesProvider();
Rules rules = provider.provide(loader);
assertThat(rules.findAll()).hasSize(1);
assertRule(rules.findAll().iterator().next());
}
private static void assertRule(org.sonar.api.batch.rule.Rule r) {
Rule testRule = getTestRule();
assertThat(r.name()).isEqualTo(testRule.getName());
assertThat(r.internalKey()).isEqualTo(testRule.getInternalKey());
assertThat(r.key().rule()).isEqualTo(testRule.getKey());
assertThat(r.key().repository()).isEqualTo(testRule.getRepository());
}
private static Rule getTestRule() {
Rule.Builder ruleBuilder = Rule.newBuilder();
ruleBuilder.setKey("key1");
ruleBuilder.setRepository("repo1");
ruleBuilder.setName("name");
ruleBuilder.setInternalKey("key1");
return ruleBuilder.build();
}
}
| 2,206 | 33.484375 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/DefaultInputModuleHierarchyTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultInputModuleHierarchyTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private DefaultInputModuleHierarchy moduleHierarchy;
@Test
public void test() throws IOException {
DefaultInputModule root = new DefaultInputModule(ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
DefaultInputModule mod1 = new DefaultInputModule(ProjectDefinition.create().setKey("mod1").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
DefaultInputModule mod2 = new DefaultInputModule(ProjectDefinition.create().setKey("mod2").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
DefaultInputModule mod3 = new DefaultInputModule(ProjectDefinition.create().setKey("mod3").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
DefaultInputModule mod4 = new DefaultInputModule(ProjectDefinition.create().setKey("mod4").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
Map<DefaultInputModule, DefaultInputModule> parents = new HashMap<>();
parents.put(mod1, root);
parents.put(mod2, mod1);
parents.put(mod3, root);
parents.put(mod4, root);
moduleHierarchy = new DefaultInputModuleHierarchy(root, parents);
assertThat(moduleHierarchy.children(root)).containsOnly(mod1, mod3, mod4);
assertThat(moduleHierarchy.children(mod4)).isEmpty();
assertThat(moduleHierarchy.children(mod1)).containsOnly(mod2);
assertThat(moduleHierarchy.parent(mod4)).isEqualTo(root);
assertThat(moduleHierarchy.parent(mod2)).isEqualTo(mod1);
assertThat(moduleHierarchy.parent(mod1)).isEqualTo(root);
assertThat(moduleHierarchy.parent(root)).isNull();
assertThat(moduleHierarchy.root()).isEqualTo(root);
}
@Test
public void testOnlyRoot() throws IOException {
DefaultInputModule root = new DefaultInputModule(ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
moduleHierarchy = new DefaultInputModuleHierarchy(root);
assertThat(moduleHierarchy.children(root)).isEmpty();
assertThat(moduleHierarchy.parent(root)).isNull();
assertThat(moduleHierarchy.root()).isEqualTo(root);
}
@Test
public void testRelativePathToRoot() throws IOException {
File rootBaseDir = temp.newFolder();
File mod1BaseDir = new File(rootBaseDir, "mod1");
File mod2BaseDir = new File(rootBaseDir, "mod2");
FileUtils.forceMkdir(mod1BaseDir);
FileUtils.forceMkdir(mod2BaseDir);
DefaultInputModule root = new DefaultInputModule(ProjectDefinition.create().setKey("root")
.setBaseDir(rootBaseDir).setWorkDir(rootBaseDir));
DefaultInputModule mod1 = new DefaultInputModule(ProjectDefinition.create().setKey("mod1")
.setBaseDir(mod1BaseDir).setWorkDir(temp.newFolder()));
DefaultInputModule mod2 = new DefaultInputModule(ProjectDefinition.create().setKey("mod2")
.setBaseDir(mod2BaseDir).setWorkDir(temp.newFolder()));
DefaultInputModule mod3 = new DefaultInputModule(ProjectDefinition.create().setKey("mod2")
.setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
Map<DefaultInputModule, DefaultInputModule> parents = new HashMap<>();
parents.put(mod1, root);
parents.put(mod2, mod1);
parents.put(mod3, mod1);
moduleHierarchy = new DefaultInputModuleHierarchy(root, parents);
assertThat(moduleHierarchy.relativePathToRoot(root)).isEmpty();
assertThat(moduleHierarchy.relativePathToRoot(mod1)).isEqualTo("mod1");
assertThat(moduleHierarchy.relativePathToRoot(mod2)).isEqualTo("mod2");
assertThat(moduleHierarchy.relativePathToRoot(mod3)).isNull();
}
}
| 4,941 | 43.522523 | 154 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/DeprecatedPropertiesWarningGeneratorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.event.Level;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.batch.bootstrapper.EnvironmentInformation;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.scanner.scan.DeprecatedPropertiesWarningGenerator.LOGIN_WARN_MESSAGE;
import static org.sonar.scanner.scan.DeprecatedPropertiesWarningGenerator.PASSWORD_WARN_MESSAGE;
import static org.sonar.scanner.scan.DeprecatedPropertiesWarningGenerator.SCANNER_DOTNET_WARN_MESSAGE;
public class DeprecatedPropertiesWarningGeneratorTest {
@Rule
public LogTester logger = new LogTester();
private final MapSettings settings = new MapSettings();
private final AnalysisWarnings analysisWarnings = Mockito.spy(AnalysisWarnings.class);
private final EnvironmentInformation environmentInformation = Mockito.mock(EnvironmentInformation.class);
private final DeprecatedPropertiesWarningGenerator underTest = new DeprecatedPropertiesWarningGenerator(settings.asConfig(),
analysisWarnings, environmentInformation);
@Before
public void setUp() throws Exception {
settings.removeProperty(CoreProperties.LOGIN);
settings.removeProperty(CoreProperties.PASSWORD);
when(environmentInformation.getKey()).thenReturn("ScannerCLI");
}
@Test
public void execute_whenUsingLogin_shouldAddWarning() {
settings.setProperty(CoreProperties.LOGIN, "test");
underTest.execute();
verify(analysisWarnings, times(1)).addUnique(LOGIN_WARN_MESSAGE);
Assertions.assertThat(logger.logs(Level.WARN)).contains(LOGIN_WARN_MESSAGE);
}
@Test
public void execute_whenUsingPassword_shouldAddWarning() {
settings.setProperty(CoreProperties.LOGIN, "test");
settings.setProperty(CoreProperties.PASSWORD, "winner winner chicken dinner");
underTest.execute();
verify(analysisWarnings, times(1)).addUnique(PASSWORD_WARN_MESSAGE);
Assertions.assertThat(logger.logs(Level.WARN)).contains(PASSWORD_WARN_MESSAGE);
}
@Test
public void execute_whenUsingLoginAndDotNetScanner_shouldAddWarning() {
settings.setProperty(CoreProperties.LOGIN, "test");
when(environmentInformation.getKey()).thenReturn("ScannerMSBuild");
underTest.execute();
verify(analysisWarnings, times(1)).addUnique(LOGIN_WARN_MESSAGE + SCANNER_DOTNET_WARN_MESSAGE);
Assertions.assertThat(logger.logs(Level.WARN)).contains(LOGIN_WARN_MESSAGE + SCANNER_DOTNET_WARN_MESSAGE);
}
@Test
public void execute_whenUsingPasswordAndDotNetScanner_shouldAddWarning() {
settings.setProperty(CoreProperties.LOGIN, "test");
settings.setProperty(CoreProperties.PASSWORD, "winner winner chicken dinner");
when(environmentInformation.getKey()).thenReturn("ScannerMSBuild");
underTest.execute();
verify(analysisWarnings, times(1)).addUnique(PASSWORD_WARN_MESSAGE + SCANNER_DOTNET_WARN_MESSAGE);
Assertions.assertThat(logger.logs(Level.WARN)).contains(PASSWORD_WARN_MESSAGE + SCANNER_DOTNET_WARN_MESSAGE);
}
@Test
public void execute_whenNotUsingLoginOrPassword_shouldNotAddWarning() {
underTest.execute();
verifyNoInteractions(analysisWarnings);
Assertions.assertThat(logger.logs(Level.WARN)).isEmpty();
}
}
| 4,461 | 38.140351 | 126 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/DirectoryLockTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class DirectoryLockTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private DirectoryLock lock;
@Before
public void setUp() {
lock = new DirectoryLock(temp.getRoot().toPath());
}
@Test
public void tryLock() {
assertThat(temp.getRoot()).isEmptyDirectory();
lock.tryLock();
assertThat(temp.getRoot().toPath().resolve(".sonar_lock")).exists();
lock.unlock();
}
@Test
public void unlockWithoutLock() {
lock.unlock();
}
@Test
public void errorTryLock() {
lock = new DirectoryLock(Paths.get("non", "existing", "path"));
assertThatThrownBy(() -> lock.tryLock())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Failed to create lock");
}
}
| 1,894 | 29.079365 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ModuleConfigurationProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.System2;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.sonar.scanner.bootstrap.GlobalServerSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ModuleConfigurationProviderTest {
private static final String GLOBAL_KEY_PROPERTIES_1 = "sonar.global.key1";
private static final String NON_GLOBAL_KEY_PROPERTIES_1 = "sonar.key1";
private static final String DEFAULT_KEY_PROPERTIES_1 = "default.key1";
private static final String GLOBAL_VALUE_PROPERTIES_1 = "Value for " + GLOBAL_KEY_PROPERTIES_1;
private static final String NON_GLOBAL_VALUE_PROPERTIES_1 = "Value for " + NON_GLOBAL_KEY_PROPERTIES_1;
private static final String DEFAULT_VALUE_1 = "Value for " + DEFAULT_KEY_PROPERTIES_1;
private static final Map<String, String> GLOBAL_SERVER_PROPERTIES = Map.of(GLOBAL_KEY_PROPERTIES_1, GLOBAL_VALUE_PROPERTIES_1);
private static final Map<String, String> PROJECT_SERVER_PROPERTIES = Map.of(NON_GLOBAL_KEY_PROPERTIES_1, NON_GLOBAL_VALUE_PROPERTIES_1);
private static final Map<String, String> DEFAULT_PROJECT_PROPERTIES = Map.of(DEFAULT_KEY_PROPERTIES_1, DEFAULT_VALUE_1);
private static final Map<String, String> ALL_PROPERTIES_MAP =
Stream.of(GLOBAL_SERVER_PROPERTIES, PROJECT_SERVER_PROPERTIES)
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
private static final Map<String, String> PROPERTIES_AFTER_FILTERING = Map.of("aKey", "aValue");
@Mock
private GlobalServerSettings globalServerSettings;
@Mock
private ProjectServerSettings projectServerSettings;
@Mock
private GlobalConfiguration globalConfiguration;
@Mock
private DefaultInputModule defaultInputProject;
@Mock
private SonarGlobalPropertiesFilter sonarGlobalPropertiesFilter;
@InjectMocks
private ModuleConfigurationProvider provider;
@Before
public void init() {
when(globalConfiguration.getDefinitions()).thenReturn(new PropertyDefinitions(System2.INSTANCE));
}
@Test
public void should_concatAllPropertiesForCallFilterAndApplyFilterChanges() {
when(globalServerSettings.properties()).thenReturn(GLOBAL_SERVER_PROPERTIES);
when(projectServerSettings.properties()).thenReturn(PROJECT_SERVER_PROPERTIES);
when(sonarGlobalPropertiesFilter.enforceOnlyServerSideSonarGlobalPropertiesAreUsed(ALL_PROPERTIES_MAP, GLOBAL_SERVER_PROPERTIES))
.thenReturn(PROPERTIES_AFTER_FILTERING);
ModuleConfiguration provide = provider.provide(globalConfiguration, defaultInputProject, globalServerSettings, projectServerSettings);
verify(sonarGlobalPropertiesFilter).enforceOnlyServerSideSonarGlobalPropertiesAreUsed(ALL_PROPERTIES_MAP, GLOBAL_SERVER_PROPERTIES);
assertThat(provide.getOriginalProperties()).containsExactlyEntriesOf(PROPERTIES_AFTER_FILTERING);
}
} | 4,238 | 42.701031 | 138 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ModuleIndexerTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import java.util.Arrays;
import org.junit.Test;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ModuleIndexerTest {
private ModuleIndexer indexer;
private DefaultInputModuleHierarchy moduleHierarchy;
public void createIndexer() {
InputComponentStore componentStore = new InputComponentStore(mock(BranchConfiguration.class), mock(SonarRuntime.class));
moduleHierarchy = mock(DefaultInputModuleHierarchy.class);
indexer = new ModuleIndexer(componentStore, moduleHierarchy);
}
@Test
public void testIndex() {
ProjectDefinition rootDef = mock(ProjectDefinition.class);
ProjectDefinition def = mock(ProjectDefinition.class);
when(rootDef.getParent()).thenReturn(null);
when(def.getParent()).thenReturn(rootDef);
DefaultInputModule root = mock(DefaultInputModule.class);
DefaultInputModule mod1 = mock(DefaultInputModule.class);
DefaultInputModule mod2 = mock(DefaultInputModule.class);
DefaultInputModule mod3 = mock(DefaultInputModule.class);
when(root.key()).thenReturn("root");
when(mod1.key()).thenReturn("mod1");
when(mod2.key()).thenReturn("mod2");
when(mod3.key()).thenReturn("mod3");
when(root.definition()).thenReturn(rootDef);
when(mod1.definition()).thenReturn(def);
when(mod2.definition()).thenReturn(def);
when(mod3.definition()).thenReturn(def);
createIndexer();
when(moduleHierarchy.root()).thenReturn(root);
when(moduleHierarchy.children(root)).thenReturn(Arrays.asList(mod1, mod2, mod3));
indexer.start();
DefaultInputModule rootModule = moduleHierarchy.root();
assertThat(rootModule).isNotNull();
assertThat(moduleHierarchy.children(rootModule)).hasSize(3);
}
}
| 2,952 | 37.350649 | 124 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectBuildersExecutorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.bootstrap.ProjectBuilder;
import org.sonar.api.batch.bootstrap.ProjectBuilder.Context;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
public class ProjectBuildersExecutorTest {
private ProjectReactor reactor;
@Before
public void setUp() {
reactor = mock(ProjectReactor.class);
}
@Test
public void testProjectBuilderFailsWithToString() {
ProjectBuilder builder = mock(ProjectBuilder.class);
doThrow(new IllegalStateException()).when(builder).build(any(Context.class));
ProjectBuilder[] projectBuilders = {builder};
assertThatThrownBy(() -> new ProjectBuildersExecutor(mock(GlobalConfiguration.class), projectBuilders).execute(reactor))
.isInstanceOf(MessageException.class)
.hasMessageContaining("Failed to execute project builder: Mock for ProjectBuilder");
}
@Test
public void testProjectBuilderFailsWithoutToString() {
ProjectBuilder[] projectBuilders = {new MyProjectBuilder()};
assertThatThrownBy(() -> new ProjectBuildersExecutor(mock(GlobalConfiguration.class), projectBuilders).execute(reactor))
.isInstanceOf(MessageException.class)
.hasMessage("Failed to execute project builder: org.sonar.scanner.scan.ProjectBuildersExecutorTest$MyProjectBuilder");
}
static class MyProjectBuilder extends ProjectBuilder {
@Override
public void build(Context context) {
throw new IllegalStateException();
}
}
}
| 2,663 | 36.521127 | 124 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectConfigurationProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.System2;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.sonar.scanner.bootstrap.GlobalServerSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ProjectConfigurationProviderTest {
private static final String GLOBAL_KEY_PROPERTIES_1 = "sonar.global.key1";
private static final String NON_GLOBAL_KEY_PROPERTIES_1 = "sonar.key1";
private static final String DEFAULT_KEY_PROPERTIES_1 = "default.key1";
private static final String GLOBAL_VALUE_PROPERTIES_1 = "Value for " + GLOBAL_KEY_PROPERTIES_1;
private static final String NON_GLOBAL_VALUE_PROPERTIES_1 = "Value for " + NON_GLOBAL_KEY_PROPERTIES_1;
private static final String DEFAULT_VALUE_1 = "Value for " + DEFAULT_KEY_PROPERTIES_1;
private static final Map<String, String> GLOBAL_SERVER_PROPERTIES = Map.of(GLOBAL_KEY_PROPERTIES_1, GLOBAL_VALUE_PROPERTIES_1);
private static final Map<String, String> PROJECT_SERVER_PROPERTIES = Map.of(NON_GLOBAL_KEY_PROPERTIES_1, NON_GLOBAL_VALUE_PROPERTIES_1);
private static final Map<String, String> DEFAULT_PROJECT_PROPERTIES = Map.of(DEFAULT_KEY_PROPERTIES_1, DEFAULT_VALUE_1);
private static final Map<String, String> ALL_PROPERTIES_MAP =
Stream.of(GLOBAL_SERVER_PROPERTIES, PROJECT_SERVER_PROPERTIES, DEFAULT_PROJECT_PROPERTIES)
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
private static final Map<String, String> PROPERTIES_AFTER_FILTERING = Map.of("aKey", "aValue");
@Mock
private GlobalServerSettings globalServerSettings;
@Mock
private ProjectServerSettings projectServerSettings;
@Mock
private GlobalConfiguration globalConfiguration;
@Mock
private MutableProjectSettings mutableProjectSettings;
@Mock
private DefaultInputProject defaultInputProject;
@Mock
private SonarGlobalPropertiesFilter sonarGlobalPropertiesFilter;
@InjectMocks
private ProjectConfigurationProvider provider;
@Before
public void init() {
when(globalConfiguration.getDefinitions()).thenReturn(new PropertyDefinitions(System2.INSTANCE));
}
@Test
public void should_concatAllPropertiesForCallFilterAndApplyFilterChanges() {
when(globalServerSettings.properties()).thenReturn(GLOBAL_SERVER_PROPERTIES);
when(projectServerSettings.properties()).thenReturn(PROJECT_SERVER_PROPERTIES);
when(defaultInputProject.properties()).thenReturn(DEFAULT_PROJECT_PROPERTIES);
when(sonarGlobalPropertiesFilter.enforceOnlyServerSideSonarGlobalPropertiesAreUsed(ALL_PROPERTIES_MAP, GLOBAL_SERVER_PROPERTIES))
.thenReturn(PROPERTIES_AFTER_FILTERING);
ProjectConfiguration provide = provider.provide(defaultInputProject, globalConfiguration, globalServerSettings, projectServerSettings, mutableProjectSettings);
verify(sonarGlobalPropertiesFilter).enforceOnlyServerSideSonarGlobalPropertiesAreUsed(ALL_PROPERTIES_MAP, GLOBAL_SERVER_PROPERTIES);
assertThat(provide.getOriginalProperties()).containsExactlyEntriesOf(PROPERTIES_AFTER_FILTERING);
}
} | 4,442 | 43.878788 | 163 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectLockTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ProjectLockTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private ProjectLock lock;
private File baseDir;
private File worDir;
@Before
public void setUp() throws IOException {
baseDir = tempFolder.newFolder();
worDir = new File(baseDir, ".sonar");
lock = new ProjectLock(new DefaultInputProject(ProjectDefinition.create().setBaseDir(baseDir).setWorkDir(worDir)));
}
@Test
public void tryLock() {
Path lockFilePath = worDir.toPath().resolve(DirectoryLock.LOCK_FILE_NAME);
lock.tryLock();
assertThat(Files.exists(lockFilePath)).isTrue();
assertThat(Files.isRegularFile(lockFilePath)).isTrue();
lock.stop();
assertThat(Files.exists(lockFilePath)).isTrue();
}
@Test
public void tryLockConcurrently() {
lock.tryLock();
assertThatThrownBy(() -> lock.tryLock())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Another SonarQube analysis is already in progress for this project");
}
@Test
/**
* If there is an error starting up the scan, we'll still try to unlock even if the lock
* was never done
*/
public void stopWithoutStarting() {
lock.stop();
lock.stop();
}
@Test
public void tryLockTwice() {
lock.tryLock();
lock.stop();
lock.tryLock();
lock.stop();
}
@Test
public void unLockWithNoLock() {
lock.stop();
}
}
| 2,738 | 27.831579 | 119 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectReactorBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.MessageException;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.bootstrap.ScannerProperties;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
public class ProjectReactorBuilderTest {
@Rule
public LogTester logTester = new LogTester();
@Test
public void shouldDefineSimpleProject() {
ProjectDefinition projectDefinition = loadProjectDefinition("simple-project");
assertThat(projectDefinition.getKey()).isEqualTo("com.foo.project");
assertThat(projectDefinition.getName()).isEqualTo("Foo Project");
assertThat(projectDefinition.getVersion()).isEqualTo("1.0-SNAPSHOT");
assertThat(projectDefinition.getDescription()).isEqualTo("Description of Foo Project");
assertThat(projectDefinition.sources()).contains("sources");
}
@Test
public void should_fail_if_sources_are_missing_in_leaf_module() {
assertThatThrownBy(() -> loadProjectDefinition("simple-project-with-unexisting-source-dir"))
.isInstanceOf(MessageException.class)
.hasMessage("The folder 'unexisting-source-dir' does not exist for 'com.foo.project' (base directory = "
+ getResource(this.getClass(), "simple-project-with-unexisting-source-dir") + ")");
}
@Test
public void should_not_fail_if_sources_are_missing_in_intermediate_module() {
assertThatNoException()
.isThrownBy(() -> loadProjectDefinition("multi-module-pom-in-root"));
}
@Test
public void shouldNotFailIfBlankSourceDirectory() {
assertThatNoException()
.isThrownBy(() -> loadProjectDefinition("simple-project-with-blank-source-dir"));
}
@Test
public void modulesDuplicateIds() {
assertThatThrownBy(() -> loadProjectDefinition("multi-module-duplicate-id"))
.isInstanceOf(MessageException.class)
.hasMessage("Two modules have the same id: 'module1'. Each module must have a unique id.");
}
@Test
public void sonarModuleIdIsForbidden() {
assertThatThrownBy(() -> loadProjectDefinition("multi-module-sonar-module"))
.isInstanceOf(MessageException.class)
.hasMessage("'sonar' is not a valid module id. Please check property 'sonar.modules'.");
}
@Test
public void modulesRepeatedIds() {
ProjectDefinition rootProject = loadProjectDefinition("multi-module-repeated-id");
List<ProjectDefinition> modules = rootProject.getSubProjects();
assertThat(modules.size()).isOne();
// Module 1
ProjectDefinition module1 = modules.get(0);
assertThat(module1.getKey()).isEqualTo("com.foo.project:module1");
assertThat(module1.getName()).isEqualTo("Foo Module 1");
// Module 1 -> Module 1
ProjectDefinition module1_module1 = module1.getSubProjects().get(0);
assertThat(module1_module1.getKey()).isEqualTo("com.foo.project:module1:module1");
assertThat(module1_module1.getName()).isEqualTo("Foo Sub Module 1");
}
@Test
public void shouldDefineMultiModuleProjectWithDefinitionsAllInRootProject() throws IOException {
execMultiModule("multi-module-definitions-all-in-root");
}
@Test
public void shouldDefineMultiModuleProjectWithPomFileAtRootLevel() throws IOException {
ProjectDefinition project = execMultiModule("multi-module-pom-in-root");
assertThat(project.sources()).containsExactlyInAnyOrder("pom.xml", "sources");
}
public ProjectDefinition execMultiModule(String key) throws IOException {
ProjectDefinition rootProject = loadProjectDefinition(key);
// CHECK ROOT
assertThat(rootProject.getKey()).isEqualTo("com.foo.project");
assertThat(rootProject.getName()).isEqualTo("Foo Project");
assertThat(rootProject.getVersion()).isEqualTo("1.0-SNAPSHOT");
assertThat(rootProject.getDescription()).isEqualTo("Description of Foo Project");
assertThat(rootProject.sources()).contains("sources");
assertThat(rootProject.tests()).contains("tests");
// and module properties must have been cleaned
assertThat(rootProject.properties().get("module1.sonar.projectKey")).isNull();
assertThat(rootProject.properties().get("module2.sonar.projectKey")).isNull();
// Check baseDir and workDir
assertThat(rootProject.getBaseDir().getCanonicalFile()).isEqualTo(getResource(this.getClass(), key));
assertThat(rootProject.getWorkDir().getCanonicalFile()).isEqualTo(new File(getResource(this.getClass(), key), ".sonar"));
// CHECK MODULES
List<ProjectDefinition> modules = rootProject.getSubProjects();
assertThat(modules).hasSize(2);
// Module 1
ProjectDefinition module1 = modules.get(0);
assertThat(module1.getBaseDir().getCanonicalFile()).isEqualTo(getResource(this.getClass(), key + "/module1"));
assertThat(module1.getKey()).isEqualTo("com.foo.project:module1");
assertThat(module1.getName()).isEqualTo("module1");
assertThat(module1.getVersion()).isEqualTo("1.0-SNAPSHOT");
// Description should not be inherited from parent if not set
assertThat(module1.getDescription()).isNull();
assertThat(module1.sources()).contains("sources");
assertThat(module1.tests()).contains("tests");
// and module properties must have been cleaned
assertThat(module1.properties().get("module1.sonar.projectKey")).isNull();
assertThat(module1.properties().get("module2.sonar.projectKey")).isNull();
// Check baseDir and workDir
assertThat(module1.getBaseDir().getCanonicalFile()).isEqualTo(getResource(this.getClass(), key + "/module1"));
assertThat(module1.getWorkDir().getCanonicalFile()).isEqualTo(new File(getResource(this.getClass(), key), ".sonar/com.foo.project_module1"));
// Module 2
ProjectDefinition module2 = modules.get(1);
assertThat(module2.getBaseDir().getCanonicalFile()).isEqualTo(getResource(this.getClass(), key + "/module2"));
assertThat(module2.getKey()).isEqualTo("com.foo.project:com.foo.project.module2");
assertThat(module2.getName()).isEqualTo("Foo Module 2");
assertThat(module2.getVersion()).isEqualTo("1.0-SNAPSHOT");
assertThat(module2.getDescription()).isEqualTo("Description of Module 2");
assertThat(module2.sources()).contains("src");
assertThat(module2.tests()).contains("tests");
// and module properties must have been cleaned
assertThat(module2.properties().get("module1.sonar.projectKey")).isNull();
assertThat(module2.properties().get("module2.sonar.projectKey")).isNull();
// Check baseDir and workDir
assertThat(module2.getBaseDir().getCanonicalFile()).isEqualTo(getResource(this.getClass(), key + "/module2"));
assertThat(module2.getWorkDir().getCanonicalFile()).isEqualTo(
new File(getResource(this.getClass(), key), ".sonar/com.foo.project_com.foo.project.module2"));
return rootProject;
}
// SONAR-4876
@Test
public void shouldDefineMultiModuleProjectWithModuleKey() {
ProjectDefinition rootProject = loadProjectDefinition("multi-module-definitions-moduleKey");
// CHECK ROOT
// module properties must have been cleaned
assertThat(rootProject.properties().get("module1.sonar.moduleKey")).isNull();
assertThat(rootProject.properties().get("module2.sonar.moduleKey")).isNull();
// CHECK MODULES
List<ProjectDefinition> modules = rootProject.getSubProjects();
assertThat(modules).hasSize(2);
// Module 2
ProjectDefinition module2 = modules.get(1);
assertThat(module2.getKey()).isEqualTo("com.foo.project.module2");
}
// SONARPLUGINS-2421
@Test
public void shouldDefineMultiLanguageProjectWithDefinitionsAllInRootProject() throws IOException {
ProjectDefinition rootProject = loadProjectDefinition("multi-language-definitions-all-in-root");
// CHECK ROOT
assertThat(rootProject.getKey()).isEqualTo("example");
assertThat(rootProject.getName()).isEqualTo("Example");
assertThat(rootProject.getVersion()).isEqualTo("1.0");
// CHECK MODULES
List<ProjectDefinition> modules = rootProject.getSubProjects();
assertThat(modules).hasSize(2);
// Module 1
ProjectDefinition module1 = modules.get(0);
assertThat(module1.getBaseDir().getCanonicalFile()).isEqualTo(getResource(this.getClass(), "multi-language-definitions-all-in-root"));
assertThat(module1.sources()).contains("src/main/java");
// and module properties must have been cleaned
assertThat(module1.getWorkDir().getCanonicalFile())
.isEqualTo(new File(getResource(this.getClass(), "multi-language-definitions-all-in-root"), ".sonar/example_java-module"));
// Module 2
ProjectDefinition module2 = modules.get(1);
assertThat(module2.getBaseDir().getCanonicalFile()).isEqualTo(getResource(this.getClass(), "multi-language-definitions-all-in-root"));
assertThat(module2.sources()).contains("src/main/groovy");
// and module properties must have been cleaned
assertThat(module2.getWorkDir().getCanonicalFile())
.isEqualTo(new File(getResource(this.getClass(), "multi-language-definitions-all-in-root"), ".sonar/example_groovy-module"));
}
@Test
public void shouldDefineMultiModuleProjectWithBaseDir() {
ProjectDefinition rootProject = loadProjectDefinition("multi-module-with-basedir");
List<ProjectDefinition> modules = rootProject.getSubProjects();
assertThat(modules.size()).isOne();
assertThat(modules.get(0).getKey()).isEqualTo("com.foo.project:com.foo.project.module1");
}
@Test
public void shouldFailIfUnexistingModuleBaseDir() {
assertThatThrownBy(() -> loadProjectDefinition("multi-module-with-unexisting-basedir"))
.isInstanceOf(MessageException.class)
.hasMessage("The base directory of the module 'module1' does not exist: "
+ getResource(this.getClass(), "multi-module-with-unexisting-basedir").getAbsolutePath() + File.separator + "module1");
}
@Test
public void shouldFailIfUnexistingSourceFolderInheritedInMultimodule() {
assertThatThrownBy(() -> loadProjectDefinition("multi-module-with-unexisting-source-dir"))
.isInstanceOf(MessageException.class)
.hasMessage("The folder 'unexisting-source-dir' does not exist for 'com.foo.project:module1' (base directory = "
+ getResource(this.getClass(), "multi-module-with-unexisting-source-dir").getAbsolutePath() + File.separator + "module1)");
}
@Test
public void shouldFailIfExplicitUnexistingTestFolder() {
assertThatThrownBy(() -> loadProjectDefinition("simple-project-with-unexisting-test-dir"))
.isInstanceOf(MessageException.class)
.hasMessageContaining("The folder 'tests' does not exist for 'com.foo.project' (base directory = "
+ getResource(this.getClass(), "simple-project-with-unexisting-test-dir").getAbsolutePath());
}
@Test
public void shouldFailIfExplicitUnexistingTestFolderOnModule() {
assertThatThrownBy(() -> loadProjectDefinition("multi-module-with-explicit-unexisting-test-dir"))
.isInstanceOf(MessageException.class)
.hasMessage("The folder 'tests' does not exist for 'module1' (base directory = "
+ getResource(this.getClass(), "multi-module-with-explicit-unexisting-test-dir").getAbsolutePath() + File.separator + "module1)");
}
@Test
public void should_fail_with_asterisks_in_sources() {
assertThatThrownBy(() -> loadProjectDefinition("simple-project-with-asterisks-in-sources"))
.isInstanceOf(MessageException.class)
.hasMessage(ProjectReactorBuilder.WILDCARDS_NOT_SUPPORTED);
}
@Test
public void should_fail_with_asterisks_in_tests() {
assertThatThrownBy(() -> loadProjectDefinition("simple-project-with-asterisks-in-tests"))
.isInstanceOf(MessageException.class)
.hasMessage(ProjectReactorBuilder.WILDCARDS_NOT_SUPPORTED);
}
@Test
public void multiModuleProperties() {
ProjectDefinition projectDefinition = loadProjectDefinition("big-multi-module-definitions-all-in-root");
assertThat(projectDefinition.properties().get("module11.property")).isNull();
ProjectDefinition module1 = null;
ProjectDefinition module2 = null;
for (ProjectDefinition prj : projectDefinition.getSubProjects()) {
if (prj.getKey().equals("com.foo.project:module1")) {
module1 = prj;
} else if (prj.getKey().equals("com.foo.project:module2")) {
module2 = prj;
}
}
assertThat(module1.properties().get("module11.property")).isNull();
assertThat(module1.properties().get("property")).isNull();
assertThat(module2.properties().get("module11.property")).isNull();
assertThat(module2.properties().get("property")).isNull();
ProjectDefinition module11 = null;
ProjectDefinition module12 = null;
for (ProjectDefinition prj : module1.getSubProjects()) {
if (prj.getKey().equals("com.foo.project:module1:module11")) {
module11 = prj;
} else if (prj.getKey().equals("com.foo.project:module1:module12")) {
module12 = prj;
}
}
assertThat(module11.properties().get("module1.module11.property")).isNull();
assertThat(module11.properties().get("module11.property")).isNull();
assertThat(module11.properties()).containsEntry("property", "My module11 property");
assertThat(module12.properties().get("module11.property")).isNull();
assertThat(module12.properties().get("property")).isNull();
}
@Test
public void shouldFailIfMandatoryPropertiesAreNotPresent() {
Map<String, String> props = new HashMap<>();
props.put("foo1", "bla");
props.put("foo4", "bla");
assertThatThrownBy(() -> ProjectReactorBuilder.checkMandatoryProperties(props, new String[] {"foo1", "foo2", "foo3"}))
.isInstanceOf(MessageException.class)
.hasMessage("You must define the following mandatory properties for 'Unknown': foo2, foo3");
}
@Test
public void shouldFailIfMandatoryPropertiesAreNotPresentButWithProjectKey() {
Map<String, String> props = new HashMap<>();
props.put("foo1", "bla");
props.put("sonar.projectKey", "my-project");
assertThatThrownBy(() -> ProjectReactorBuilder.checkMandatoryProperties(props, new String[] {"foo1", "foo2", "foo3"}))
.isInstanceOf(MessageException.class)
.hasMessage("You must define the following mandatory properties for 'my-project': foo2, foo3");
}
@Test
public void shouldNotFailIfMandatoryPropertiesArePresent() {
Map<String, String> props = new HashMap<>();
props.put("foo1", "bla");
props.put("foo4", "bla");
ProjectReactorBuilder.checkMandatoryProperties(props, new String[] {"foo1"});
// No exception should be thrown
}
@Test
public void shouldGetRelativeFile() {
assertThat(ProjectReactorBuilder.resolvePath(getResource(this.getClass(), "/"), "shouldGetFile/foo.properties"))
.isEqualTo(getResource(this.getClass(), "shouldGetFile/foo.properties"));
}
@Test
public void shouldGetAbsoluteFile() {
File file = getResource(this.getClass(), "shouldGetFile/foo.properties");
assertThat(ProjectReactorBuilder.resolvePath(getResource(this.getClass(), "/"), file.getAbsolutePath()))
.isEqualTo(file);
}
@Test
public void shouldMergeParentProperties() {
// Use a random value to avoid VM optimization that would create constant String and make s1 and s2 the same object
int i = (int) Math.random() * 10;
String s1 = "value" + i;
String s2 = "value" + i;
Map<String, String> parentProps = new HashMap<>();
parentProps.put("toBeMergeProps", "fooParent");
parentProps.put("existingChildProp", "barParent");
parentProps.put("duplicatedProp", s1);
parentProps.put("sonar.projectDescription", "Desc from Parent");
Map<String, String> childProps = new HashMap<>();
childProps.put("existingChildProp", "barChild");
childProps.put("otherProp", "tutuChild");
childProps.put("duplicatedProp", s2);
ProjectReactorBuilder.mergeParentProperties(childProps, parentProps);
assertThat(childProps)
.hasSize(4)
.containsEntry("toBeMergeProps", "fooParent")
.containsEntry("existingChildProp", "barChild")
.containsEntry("otherProp", "tutuChild");
assertThat(childProps.get("sonar.projectDescription")).isNull();
assertThat(childProps.get("duplicatedProp")).isSameAs(parentProps.get("duplicatedProp"));
}
@Test
public void shouldInitRootWorkDir() {
ProjectReactorBuilder builder = new ProjectReactorBuilder(new ScannerProperties(emptyMap()),
mock(AnalysisWarnings.class));
File baseDir = new File("target/tmp/baseDir");
File workDir = builder.initRootProjectWorkDir(baseDir, emptyMap());
assertThat(workDir).isEqualTo(new File(baseDir, ".sonar"));
}
@Test
public void shouldInitWorkDirWithCustomRelativeFolder() {
Map<String, String> props = singletonMap("sonar.working.directory", ".foo");
ProjectReactorBuilder builder = new ProjectReactorBuilder(new ScannerProperties(props),
mock(AnalysisWarnings.class));
File baseDir = new File("target/tmp/baseDir");
File workDir = builder.initRootProjectWorkDir(baseDir, props);
assertThat(workDir).isEqualTo(new File(baseDir, ".foo"));
}
@Test
public void shouldInitRootWorkDirWithCustomAbsoluteFolder() {
Map<String, String> props = singletonMap("sonar.working.directory", new File("src").getAbsolutePath());
ProjectReactorBuilder builder = new ProjectReactorBuilder(new ScannerProperties(props),
mock(AnalysisWarnings.class));
File baseDir = new File("target/tmp/baseDir");
File workDir = builder.initRootProjectWorkDir(baseDir, props);
assertThat(workDir).isEqualTo(new File("src").getAbsoluteFile());
}
@Test
public void shouldFailIf2ModulesWithSameKey() {
Map<String, String> props = singletonMap("sonar.projectKey", "root");
ProjectDefinition root = ProjectDefinition.create().setProperties(props);
Map<String, String> props1 = singletonMap("sonar.projectKey", "mod1");
root.addSubProject(ProjectDefinition.create().setProperties(props1));
// Check uniqueness of a new module: OK
Map<String, String> props2 = singletonMap("sonar.projectKey", "mod2");
ProjectDefinition mod2 = ProjectDefinition.create().setProperties(props2);
ProjectReactorBuilder.checkUniquenessOfChildKey(mod2, root);
// Now, add it and check again
root.addSubProject(mod2);
assertThatThrownBy(() -> ProjectReactorBuilder.checkUniquenessOfChildKey(mod2, root))
.isInstanceOf(MessageException.class)
.hasMessage("Project 'root' can't have 2 modules with the following key: mod2");
}
@Test
public void shouldAcceptNoProjectName() {
ProjectDefinition rootProject = loadProjectDefinition("simple-project-with-missing-project-name");
assertThat(rootProject.getOriginalName()).isNull();
assertThat(rootProject.getName()).isEqualTo("com.foo.project");
}
@Test
public void shouldSetModuleKeyIfNotPresent() {
Map<String, String> props = new HashMap<>();
props.put("sonar.projectVersion", "1.0");
// should be set
ProjectReactorBuilder.setModuleKeyAndNameIfNotDefined(props, "foo", "parent");
assertThat(props)
.containsEntry("sonar.moduleKey", "parent:foo")
.containsEntry("sonar.projectName", "foo");
// but not this 2nd time
ProjectReactorBuilder.setModuleKeyAndNameIfNotDefined(props, "bar", "parent");
assertThat(props)
.containsEntry("sonar.moduleKey", "parent:foo")
.containsEntry("sonar.projectName", "foo");
}
private ProjectDefinition loadProjectDefinition(String projectFolder) {
Map<String, String> props = loadProps(projectFolder);
ScannerProperties bootstrapProps = new ScannerProperties(props);
ProjectReactor projectReactor = new ProjectReactorBuilder(bootstrapProps, mock(AnalysisWarnings.class)).execute();
return projectReactor.getRoot();
}
protected static Properties toProperties(File propertyFile) {
Properties propsFromFile = new Properties();
try (FileInputStream fileInputStream = new FileInputStream(propertyFile)) {
propsFromFile.load(fileInputStream);
} catch (IOException e) {
throw new IllegalStateException("Impossible to read the property file: " + propertyFile.getAbsolutePath(), e);
}
// Trim properties
for (String propKey : propsFromFile.stringPropertyNames()) {
propsFromFile.setProperty(propKey, StringUtils.trim(propsFromFile.getProperty(propKey)));
}
return propsFromFile;
}
private Map<String, String> loadProps(String projectFolder) {
Map<String, String> props = new HashMap<>();
Properties runnerProps = toProperties(getResource(this.getClass(), projectFolder + "/sonar-project.properties"));
for (final String name : runnerProps.stringPropertyNames()) {
props.put(name, runnerProps.getProperty(name));
}
props.put("sonar.projectBaseDir", getResource(this.getClass(), projectFolder).getAbsolutePath());
return props;
}
@Test
public void shouldGetList() {
Map<String, String> props = new HashMap<>();
props.put("prop", " foo ,, bar , toto,tutu");
assertThat(ProjectReactorBuilder.getListFromProperty(props, "prop")).containsOnly("foo", "bar", "toto", "tutu");
}
@Test
public void shouldGetListWithComma() {
Map<String, String> props = new HashMap<>();
props.put("prop", "\"foo,bar\", toto,tutu");
assertThat(ProjectReactorBuilder.getListFromProperty(props, "prop")).containsOnly("foo,bar", "toto", "tutu");
}
@Test
public void shouldGetEmptyList() {
Map<String, String> props = new HashMap<>();
props.put("prop", "");
assertThat(ProjectReactorBuilder.getListFromProperty(props, "prop")).isEmpty();
}
@Test
public void shouldGetListFromFile() throws IOException {
String filePath = "shouldGetList/foo.properties";
Map<String, String> props = loadPropsFromFile(filePath);
assertThat(ProjectReactorBuilder.getListFromProperty(props, "prop")).containsOnly("foo", "bar", "toto", "tutu");
}
@Test
public void doNotMixPropertiesWhenModuleKeyIsPrefixOfAnother() throws IOException {
ProjectDefinition rootProject = loadProjectDefinition("multi-module-definitions-same-prefix");
// CHECK ROOT
assertThat(rootProject.getKey()).isEqualTo("com.foo.project");
assertThat(rootProject.getName()).isEqualTo("Foo Project");
assertThat(rootProject.getVersion()).isEqualTo("1.0-SNAPSHOT");
assertThat(rootProject.getDescription()).isEqualTo("Description of Foo Project");
assertThat(rootProject.sources()).contains("sources");
assertThat(rootProject.tests()).contains("tests");
// Module properties must have been cleaned
assertThat(rootProject.properties().get("module1.sonar.projectKey")).isNull();
assertThat(rootProject.properties().get("module2.sonar.projectKey")).isNull();
// Check baseDir and workDir
assertThat(rootProject.getBaseDir().getCanonicalFile())
.isEqualTo(getResource(this.getClass(), "multi-module-definitions-same-prefix"));
assertThat(rootProject.getWorkDir().getCanonicalFile())
.isEqualTo(new File(getResource(this.getClass(), "multi-module-definitions-same-prefix"), ".sonar"));
// CHECK MODULES
List<ProjectDefinition> modules = rootProject.getSubProjects();
assertThat(modules).hasSize(2);
// Module 1
ProjectDefinition module1 = modules.get(0);
assertThat(module1.getBaseDir().getCanonicalFile()).isEqualTo(getResource(this.getClass(), "multi-module-definitions-same-prefix/module1"));
assertThat(module1.getKey()).isEqualTo("com.foo.project:module1");
assertThat(module1.getName()).isEqualTo("module1");
assertThat(module1.getVersion()).isEqualTo("1.0-SNAPSHOT");
// Description should not be inherited from parent if not set
assertThat(module1.getDescription()).isNull();
assertThat(module1.sources()).contains("sources");
assertThat(module1.tests()).contains("tests");
// and module properties must have been cleaned
assertThat(module1.properties().get("module1.sonar.projectKey")).isNull();
assertThat(module1.properties().get("module2.sonar.projectKey")).isNull();
// Check baseDir and workDir
assertThat(module1.getBaseDir().getCanonicalFile())
.isEqualTo(getResource(this.getClass(), "multi-module-definitions-same-prefix/module1"));
assertThat(module1.getWorkDir().getCanonicalFile())
.isEqualTo(new File(getResource(this.getClass(), "multi-module-definitions-same-prefix"), ".sonar/com.foo.project_module1"));
// Module 1 Feature
ProjectDefinition module1Feature = modules.get(1);
assertThat(module1Feature.getBaseDir().getCanonicalFile()).isEqualTo(getResource(this.getClass(), "multi-module-definitions-same-prefix/module1.feature"));
assertThat(module1Feature.getKey()).isEqualTo("com.foo.project:com.foo.project.module1.feature");
assertThat(module1Feature.getName()).isEqualTo("Foo Module 1 Feature");
assertThat(module1Feature.getVersion()).isEqualTo("1.0-SNAPSHOT");
assertThat(module1Feature.getDescription()).isEqualTo("Description of Module 1 Feature");
assertThat(module1Feature.sources()).contains("src");
assertThat(module1Feature.tests()).contains("tests");
// and module properties must have been cleaned
assertThat(module1Feature.properties().get("module1.sonar.projectKey")).isNull();
assertThat(module1Feature.properties().get("module2.sonar.projectKey")).isNull();
// Check baseDir and workDir
assertThat(module1Feature.getBaseDir().getCanonicalFile())
.isEqualTo(getResource(this.getClass(), "multi-module-definitions-same-prefix/module1.feature"));
assertThat(module1Feature.getWorkDir().getCanonicalFile())
.isEqualTo(new File(getResource(this.getClass(), "multi-module-definitions-same-prefix"), ".sonar/com.foo.project_com.foo.project.module1.feature"));
}
private Map<String, String> loadPropsFromFile(String filePath) throws IOException {
Properties props = new Properties();
try (FileInputStream fileInputStream = new FileInputStream(getResource(this.getClass(), filePath))) {
props.load(fileInputStream);
}
Map<String, String> result = new HashMap<>();
for (Map.Entry<Object, Object> entry : props.entrySet()) {
result.put(entry.getKey().toString(), entry.getValue().toString());
}
return result;
}
/**
* Search for a test resource in the classpath. For example getResource("org/sonar/MyClass/foo.txt");
*
* @param path the starting slash is optional
* @return the resource. Null if resource not found
*/
public static File getResource(String path) {
String resourcePath = path;
if (!resourcePath.startsWith("/")) {
resourcePath = "/" + resourcePath;
}
URL url = ProjectReactorBuilderTest.class.getResource(resourcePath);
if (url != null) {
return FileUtils.toFile(url);
}
return null;
}
/**
* Search for a resource in the classpath. For example calling the method getResource(getClass(), "myTestName/foo.txt") from
* the class org.sonar.Foo loads the file $basedir/src/test/resources/org/sonar/Foo/myTestName/foo.txt
*
* @return the resource. Null if resource not found
*/
public static File getResource(Class baseClass, String path) {
String resourcePath = StringUtils.replaceChars(baseClass.getCanonicalName(), '.', '/');
if (!path.startsWith("/")) {
resourcePath += "/";
}
resourcePath += path;
return getResource(resourcePath);
}
}
| 28,965 | 43.631741 | 159 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectReactorValidatorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.utils.MessageException;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.config.ScannerProperties;
import org.sonar.core.documentation.DefaultDocumentationLinkGenerator;
import org.sonar.scanner.ProjectInfo;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import static java.lang.String.format;
import static org.apache.commons.lang.RandomStringUtils.randomAscii;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.core.config.ScannerProperties.BRANCHES_DOC_LINK_SUFFIX;
@RunWith(DataProviderRunner.class)
public class ProjectReactorValidatorTest {
@Rule
public LogTester logTester = new LogTester();
private final GlobalConfiguration settings = mock(GlobalConfiguration.class);
private final ProjectInfo projectInfo = mock(ProjectInfo.class);
private final DefaultDocumentationLinkGenerator defaultDocumentationLinkGenerator = mock(DefaultDocumentationLinkGenerator.class);
private final ProjectReactorValidator underTest = new ProjectReactorValidator(settings, defaultDocumentationLinkGenerator);
private static final String LINK_TO_DOC = "link_to_documentation";
@Before
public void prepare() {
when(settings.get(anyString())).thenReturn(Optional.empty());
when(defaultDocumentationLinkGenerator.getDocumentationLink(BRANCHES_DOC_LINK_SUFFIX)).thenReturn(LINK_TO_DOC);
}
@Test
@UseDataProvider("validKeys")
public void not_fail_with_valid_key(String validKey) {
ProjectReactor projectReactor = createProjectReactor(validKey);
underTest.validate(projectReactor);
}
@DataProvider
public static Object[][] validKeys() {
return new Object[][] {
{"foo"},
{"123foo"},
{"foo123"},
{"1Z3"},
{"a123"},
{"123a"},
{"1:2"},
{"3-3"},
{"-:"},
{"Foobar2"},
{"foo.bar"},
{"foo-bar"},
{"foo:bar"},
{"foo_bar"}
};
}
@Test
public void fail_when_invalid_key() {
ProjectReactor reactor = createProjectReactor("foo$bar");
assertThatThrownBy(() -> underTest.validate(reactor))
.isInstanceOf(MessageException.class)
.hasMessageContaining("\"foo$bar\" is not a valid project key. Allowed characters are alphanumeric,"
+ " '-', '_', '.' and ':', with at least one non-digit.");
}
@Test
public void fail_when_only_digits() {
ProjectReactor reactor = createProjectReactor("12345");
assertThatThrownBy(() -> underTest.validate(reactor))
.isInstanceOf(MessageException.class)
.hasMessageContaining("\"12345\" is not a valid project key. Allowed characters are alphanumeric, "
+ "'-', '_', '.' and ':', with at least one non-digit.");
}
@Test
public void fail_when_backslash_in_key() {
ProjectReactor reactor = createProjectReactor("foo\\bar");
assertThatThrownBy(() -> underTest.validate(reactor))
.isInstanceOf(MessageException.class)
.hasMessageContaining("\"foo\\bar\" is not a valid project key. Allowed characters are alphanumeric, "
+ "'-', '_', '.' and ':', with at least one non-digit.");
}
@Test
public void fail_when_branch_name_is_specified_but_branch_plugin_not_present() {
ProjectDefinition def = ProjectDefinition.create().setProperty(CoreProperties.PROJECT_KEY_PROPERTY, "foo");
ProjectReactor reactor = new ProjectReactor(def);
when(settings.get(ScannerProperties.BRANCH_NAME)).thenReturn(Optional.of("feature1"));
assertThatThrownBy(() -> underTest.validate(reactor))
.isInstanceOf(MessageException.class)
.hasMessageContaining(format("To use the property \"sonar.branch.name\" and analyze branches, Developer Edition or above is required. See %s for more information.",
LINK_TO_DOC));
}
@Test
public void fail_when_pull_request_id_specified_but_branch_plugin_not_present() {
ProjectDefinition def = ProjectDefinition.create().setProperty(CoreProperties.PROJECT_KEY_PROPERTY, "foo");
ProjectReactor reactor = new ProjectReactor(def);
when(settings.get(ScannerProperties.PULL_REQUEST_KEY)).thenReturn(Optional.of("#1984"));
assertThatThrownBy(() -> underTest.validate(reactor))
.isInstanceOf(MessageException.class)
.hasMessageContaining(format("To use the property \"sonar.pullrequest.key\" and analyze pull requests, Developer Edition or above is required. See %s for more information.",
LINK_TO_DOC));
}
@Test
public void fail_when_pull_request_branch_is_specified_but_branch_plugin_not_present() {
ProjectDefinition def = ProjectDefinition.create().setProperty(CoreProperties.PROJECT_KEY_PROPERTY, "foo");
ProjectReactor reactor = new ProjectReactor(def);
when(settings.get(ScannerProperties.PULL_REQUEST_BRANCH)).thenReturn(Optional.of("feature1"));
assertThatThrownBy(() -> underTest.validate(reactor))
.isInstanceOf(MessageException.class)
.hasMessageContaining(format("To use the property \"sonar.pullrequest.branch\" and analyze pull requests, Developer Edition or above is required. See %s for more information.",
LINK_TO_DOC));
}
@Test
public void fail_when_pull_request_base_specified_but_branch_plugin_not_present() {
ProjectDefinition def = ProjectDefinition.create().setProperty(CoreProperties.PROJECT_KEY_PROPERTY, "foo");
ProjectReactor reactor = new ProjectReactor(def);
when(settings.get(ScannerProperties.PULL_REQUEST_BASE)).thenReturn(Optional.of("feature1"));
assertThatThrownBy(() -> underTest.validate(reactor))
.isInstanceOf(MessageException.class)
.hasMessageContaining(format("To use the property \"sonar.pullrequest.base\" and analyze pull requests, Developer Edition or above is required. See %s for more information.",
LINK_TO_DOC));
}
@Test
@UseDataProvider("validVersions")
public void not_fail_with_valid_version(@Nullable String validVersion) {
when(projectInfo.getProjectVersion()).thenReturn(Optional.ofNullable(validVersion));
ProjectReactor projectReactor = createProjectReactor("foo");
underTest.validate(projectReactor);
}
@DataProvider
public static Object[][] validVersions() {
return new Object[][] {
{null},
{"1.0"},
{"2017-10-16"},
{randomAscii(100)}
};
}
@Test
@UseDataProvider("validBuildStrings")
public void not_fail_with_valid_buildString(@Nullable String validBuildString) {
when(projectInfo.getBuildString()).thenReturn(Optional.ofNullable(validBuildString));
ProjectReactor projectReactor = createProjectReactor("foo");
underTest.validate(projectReactor);
}
@DataProvider
public static Object[][] validBuildStrings() {
return new Object[][] {
{null},
{"1.0"},
{"2017-10-16"},
{randomAscii(100)}
};
}
private ProjectReactor createProjectReactor(String projectKey, Consumer<ProjectDefinition>... consumers) {
ProjectDefinition def = ProjectDefinition.create()
.setProperty(CoreProperties.PROJECT_KEY_PROPERTY, projectKey);
Arrays.stream(consumers).forEach(c -> c.accept(def));
return new ProjectReactor(def);
}
}
| 8,687 | 37.959641 | 182 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ScanPropertiesTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.MessageException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ScanPropertiesTest {
private final MapSettings settings = new MapSettings();
private final DefaultInputProject project = mock(DefaultInputProject.class);
private final ScanProperties underTest = new ScanProperties(settings.asConfig(), project);
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Before
public void setUp() throws IOException {
when(project.getBaseDir()).thenReturn(temp.newFolder().toPath());
when(project.getWorkDir()).thenReturn(temp.newFolder().toPath());
}
@Test
public void defaults_if_no_setting_defined() {
assertThat(underTest.branch()).isEmpty();
assertThat(underTest.preloadFileMetadata()).isFalse();
assertThat(underTest.shouldKeepReport()).isFalse();
assertThat(underTest.metadataFilePath()).isEqualTo(project.getWorkDir().resolve("report-task.txt"));
underTest.validate();
}
@Test
public void should_define_branch_name() {
settings.setProperty("sonar.branch.name", "name");
assertThat(underTest.branch()).isEqualTo(Optional.of("name"));
}
@Test
public void should_define_report_publish_timeout() {
assertThat(underTest.reportPublishTimeout()).isEqualTo(60);
settings.setProperty("sonar.ws.report.timeout", "10");
assertThat(underTest.reportPublishTimeout()).isEqualTo(10);
}
@Test
public void should_define_preload_file_metadata() {
settings.setProperty("sonar.preloadFileMetadata", "true");
assertThat(underTest.preloadFileMetadata()).isTrue();
}
@Test
public void should_define_keep_report() {
settings.setProperty("sonar.scanner.keepReport", "true");
assertThat(underTest.shouldKeepReport()).isTrue();
}
@Test
public void should_define_metadata_file_path() throws IOException {
Path path = temp.newFolder().toPath().resolve("report");
settings.setProperty("sonar.scanner.metadataFilePath", path.toString());
assertThat(underTest.metadataFilePath()).isEqualTo(path);
}
@Test
public void validate_fails_if_metadata_file_location_is_not_absolute() {
settings.setProperty("sonar.scanner.metadataFilePath", "relative");
assertThatThrownBy(() -> underTest.validate())
.isInstanceOf(MessageException.class)
.hasMessage("Property 'sonar.scanner.metadataFilePath' must point to an absolute path: relative");
}
}
| 3,753 | 35.446602 | 104 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/SonarGlobalPropertiesFilterTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.scanner.scan.SonarGlobalPropertiesFilter.SONAR_GLOBAL_PROPERTIES_PREFIX;
public class SonarGlobalPropertiesFilterTest {
private static final String SONAR_GLOBAL_KEY_1 = SONAR_GLOBAL_PROPERTIES_PREFIX + "key1";
private static final String SONAR_GLOBAL_VALUE_1 = "value for " + SONAR_GLOBAL_KEY_1;
private static final String SONAR_GLOBAL_KEY_2 = SONAR_GLOBAL_PROPERTIES_PREFIX + "key2";
private static final String SONAR_GLOBAL_KEY_3 = SONAR_GLOBAL_PROPERTIES_PREFIX + "key3";
private static final String SONAR_GLOBAL_VALUE_3 = "value for " + SONAR_GLOBAL_KEY_3;
private static final String SONAR_NON_GLOBAL_KEY_4 = "sonar.key4";
private static final String SONAR_NON_GLOBAL_VALUE_4 = "value for " + SONAR_NON_GLOBAL_KEY_4;
private static final String ANOTHER_KEY = "another key";
private static final String ANOTHER_VALUE = "another value";
private final SonarGlobalPropertiesFilter sonarGlobalPropertiesFilter = new SonarGlobalPropertiesFilter();
@Test
public void should_filterSonarGlobalProperties() {
Map<String, String> settingProperties = Map.of(
SONAR_GLOBAL_KEY_1, "shouldBeOverride",
SONAR_GLOBAL_KEY_2, "shouldBeRemove",
SONAR_NON_GLOBAL_KEY_4, SONAR_NON_GLOBAL_VALUE_4,
ANOTHER_KEY, ANOTHER_VALUE);
Map<String, String> globalServerSettingsProperties = Map.of(
SONAR_GLOBAL_KEY_1, SONAR_GLOBAL_VALUE_1,
SONAR_GLOBAL_KEY_3, SONAR_GLOBAL_VALUE_3,
SONAR_NON_GLOBAL_KEY_4, "shouldBeIgnored"
);
Map<String, String> properties = sonarGlobalPropertiesFilter.enforceOnlyServerSideSonarGlobalPropertiesAreUsed(settingProperties, globalServerSettingsProperties);
assertThat(properties).hasSize(4)
.containsEntry(SONAR_GLOBAL_KEY_1, SONAR_GLOBAL_VALUE_1)
.containsEntry(SONAR_GLOBAL_KEY_3, SONAR_GLOBAL_VALUE_3)
.containsEntry(SONAR_NON_GLOBAL_KEY_4, SONAR_NON_GLOBAL_VALUE_4)
.containsEntry(ANOTHER_KEY, ANOTHER_VALUE);
}
} | 2,949 | 43.029851 | 166 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/SpringProjectScanContainerTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import org.junit.Test;
import org.sonar.api.batch.InstantiationStrategy;
import org.sonar.api.batch.ScannerSide;
import org.sonar.api.server.ServerSide;
import org.sonar.scanner.bootstrap.ExtensionMatcher;
import static org.assertj.core.api.Assertions.assertThat;
public class SpringProjectScanContainerTest {
@Test
public void should_add_only_batch_extensions() {
ExtensionMatcher filter = SpringProjectScanContainer.getScannerProjectExtensionsFilter();
assertThat(filter.accept(new MyBatchExtension())).isTrue();
assertThat(filter.accept(MyBatchExtension.class)).isTrue();
assertThat(filter.accept(new MyProjectExtension())).isFalse();
assertThat(filter.accept(MyProjectExtension.class)).isFalse();
assertThat(filter.accept(new MyServerExtension())).isFalse();
assertThat(filter.accept(MyServerExtension.class)).isFalse();
}
@ScannerSide
@InstantiationStrategy(InstantiationStrategy.PER_BATCH)
static class MyBatchExtension {
}
@ScannerSide
@InstantiationStrategy(InstantiationStrategy.PER_PROJECT)
static class MyProjectExtension {
}
@ServerSide
static class MyServerExtension {
}
}
| 2,029 | 31.741935 | 93 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/WorkDirectoriesInitializerTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.scanner.fs.InputModuleHierarchy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class WorkDirectoriesInitializerTest {
private final WorkDirectoriesInitializer initializer = new WorkDirectoriesInitializer();
private final InputModuleHierarchy hierarchy = mock(InputModuleHierarchy.class);
private final DefaultInputProject project = mock(DefaultInputProject.class);
private final DefaultInputModule root = mock(DefaultInputModule.class);
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File rootWorkDir;
private File lock;
@Before
public void setUp() throws IOException {
rootWorkDir = temp.newFolder();
when(hierarchy.root()).thenReturn(root);
createFilesToClean(rootWorkDir);
when(root.getWorkDir()).thenReturn(rootWorkDir.toPath());
when(project.getWorkDir()).thenReturn(rootWorkDir.toPath());
}
private void createFilesToClean(File dir) throws IOException {
new File(dir, "foo.txt").createNewFile();
File newFolder = new File(dir, "foo");
newFolder.mkdir();
File fileInFolder = new File(newFolder, "test");
fileInFolder.createNewFile();
lock = new File(dir, DirectoryLock.LOCK_FILE_NAME);
lock.createNewFile();
assertThat(dir.list()).hasSizeGreaterThan(1);
}
@Test
public void execute_doesnt_fail_if_nothing_to_clean() {
temp.delete();
initializer.execute(hierarchy);
}
@Test
public void execute_should_clean_root() {
initializer.execute(project);
assertThat(rootWorkDir).exists();
assertThat(lock).exists();
assertThat(rootWorkDir.list()).containsOnly(DirectoryLock.LOCK_FILE_NAME);
}
@Test
public void execute_on_hierarchy_should_clean_submodules() throws IOException {
DefaultInputModule moduleA = mock(DefaultInputModule.class);
DefaultInputModule moduleB = mock(DefaultInputModule.class);
when(hierarchy.children(root)).thenReturn(Arrays.asList(moduleA));
when(hierarchy.children(moduleA)).thenReturn(Arrays.asList(moduleB));
File moduleAWorkdir = new File(rootWorkDir, "moduleA");
File moduleBWorkdir = new File(moduleAWorkdir, "moduleB");
when(moduleA.getWorkDir()).thenReturn(moduleAWorkdir.toPath());
when(moduleB.getWorkDir()).thenReturn(moduleBWorkdir.toPath());
moduleAWorkdir.mkdir();
moduleBWorkdir.mkdir();
new File(moduleAWorkdir, "fooA.txt").createNewFile();
new File(moduleBWorkdir, "fooB.txt").createNewFile();
initializer.execute(project);
initializer.execute(hierarchy);
assertThat(rootWorkDir).exists();
assertThat(lock).exists();
assertThat(rootWorkDir.list()).containsOnly(DirectoryLock.LOCK_FILE_NAME, "moduleA");
assertThat(moduleAWorkdir).exists();
assertThat(moduleBWorkdir).exists();
assertThat(moduleAWorkdir.list()).containsOnly("moduleB");
assertThat(moduleBWorkdir).isEmptyDirectory();
}
@Test
public void execute_on_hierarchy_should_clean_submodules_expect_submodule_with_same_work_directory_as_root() throws IOException {
DefaultInputModule moduleA = mock(DefaultInputModule.class);
DefaultInputModule moduleB = mock(DefaultInputModule.class);
when(hierarchy.children(root)).thenReturn(List.of(moduleA, moduleB));
File rootAndModuleAWorkdir = new File(rootWorkDir, "moduleA");
File moduleBWorkdir = new File(rootAndModuleAWorkdir, "../moduleB");
when(root.getWorkDir()).thenReturn(rootAndModuleAWorkdir.toPath());
when(moduleA.getWorkDir()).thenReturn(rootAndModuleAWorkdir.toPath());
when(moduleB.getWorkDir()).thenReturn(moduleBWorkdir.toPath());
rootAndModuleAWorkdir.mkdir();
createFilesToClean(rootAndModuleAWorkdir);
moduleBWorkdir.mkdir();
new File(rootAndModuleAWorkdir, "fooA.txt").createNewFile();
new File(moduleBWorkdir, "fooB.txt").createNewFile();
initializer.execute(hierarchy);
assertThat(rootWorkDir).exists();
assertThat(lock).exists();
assertThat(rootAndModuleAWorkdir).exists();
assertThat(rootAndModuleAWorkdir.list()).containsOnly(DirectoryLock.LOCK_FILE_NAME, "fooA.txt", "foo", "foo.txt");
assertThat(moduleBWorkdir)
.exists()
.isEmptyDirectory();
}
}
| 5,477 | 35.278146 | 131 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/branch/BranchConfigurationProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.branch;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.scanner.scan.ProjectConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BranchConfigurationProviderTest {
private BranchConfigurationProvider provider = new BranchConfigurationProvider();
private ProjectConfiguration projectConfiguration = mock(ProjectConfiguration.class);
private BranchConfigurationLoader loader = mock(BranchConfigurationLoader.class);
private BranchConfiguration config = mock(BranchConfiguration.class);
private ProjectBranches branches = mock(ProjectBranches.class);
private ProjectReactor reactor = mock(ProjectReactor.class);
private Map<String, String> projectSettings = new HashMap<>();
private ProjectDefinition root = mock(ProjectDefinition.class);
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(projectConfiguration.getProperties()).thenReturn(projectSettings);
when(reactor.getRoot()).thenReturn(root);
}
@Test
public void should_use_loader() {
when(loader.load(eq(projectSettings), eq(branches))).thenReturn(config);
BranchConfiguration result = provider.provide(loader, projectConfiguration, branches);
assertThat(result).isSameAs(config);
}
@Test
public void should_return_default_if_no_loader() {
BranchConfiguration result = provider.provide(null, projectConfiguration, branches);
assertThat(result.targetBranchName()).isNull();
assertThat(result.branchType()).isEqualTo(BranchType.BRANCH);
}
}
| 2,738 | 38.128571 | 90 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/branch/ProjectBranchesProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.branch;
import org.junit.Before;
import org.junit.Test;
import org.sonar.scanner.bootstrap.ScannerProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ProjectBranchesProviderTest {
private ProjectBranchesProvider provider = new ProjectBranchesProvider();
private ProjectBranchesLoader mockLoader;
private ProjectBranches mockBranches;
private ScannerProperties scannerProperties;
@Before
public void setUp() {
mockLoader = mock(ProjectBranchesLoader.class);
mockBranches = mock(ProjectBranches.class);
scannerProperties = mock(ScannerProperties.class);
}
@Test
public void should_use_loader() {
when(scannerProperties.getProjectKey()).thenReturn("key");
when(mockLoader.load("key")).thenReturn(mockBranches);
ProjectBranches branches = provider.provide(mockLoader, scannerProperties);
assertThat(branches).isSameAs(mockBranches);
}
@Test
public void should_return_default_if_no_loader() {
ProjectBranches branches = provider.provide(null, scannerProperties);
assertThat(branches.isEmpty()).isTrue();
}
}
| 2,058 | 33.898305 | 79 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/branch/ProjectBranchesTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.branch;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(DataProviderRunner.class)
public class ProjectBranchesTest {
private static final BranchInfo mainBranch = new BranchInfo("main", BranchType.BRANCH, true, null);
private static final BranchInfo branch = new BranchInfo("branch", BranchType.BRANCH, false, null);
private static final BranchInfo pullRequest = new BranchInfo("pull-request", BranchType.PULL_REQUEST, false, null);
private static final List<BranchInfo> nonMainBranches = Arrays.asList(branch, pullRequest);
private static final List<BranchInfo> allBranches = Arrays.asList(branch, pullRequest, mainBranch);
private final ProjectBranches underTest = new ProjectBranches(allBranches);
@Test
public void defaultBranchName() {
for (int i = 0; i <= nonMainBranches.size(); i++) {
List<BranchInfo> branches = new ArrayList<>(nonMainBranches);
branches.add(i, mainBranch);
assertThat(new ProjectBranches(branches).defaultBranchName()).isEqualTo(mainBranch.name());
}
}
@Test
@UseDataProvider("branchNamesAndBranches")
public void get(String branchName, BranchInfo branchInfo) {
assertThat(underTest.get(branchName)).isEqualTo(branchInfo);
}
@DataProvider
public static Object[][] branchNamesAndBranches() {
return allBranches.stream()
.map(b -> new Object[] {b.name(), b})
.toArray(Object[][]::new);
}
@Test
public void isEmpty() {
assertThat(underTest.isEmpty()).isFalse();
assertThat(new ProjectBranches(Collections.emptyList()).isEmpty()).isTrue();
assertThat(new ProjectBranches(Collections.emptyList()).defaultBranchName()).isEqualTo("main");
}
}
| 2,904 | 37.223684 | 117 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/AbstractExclusionFiltersTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.filesystem;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.batch.fs.IndexedFile;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultIndexedFile;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.sonar.api.CoreProperties.PROJECT_TESTS_EXCLUSIONS_PROPERTY;
import static org.sonar.api.CoreProperties.PROJECT_TESTS_INCLUSIONS_PROPERTY;
import static org.sonar.api.CoreProperties.PROJECT_TEST_EXCLUSIONS_PROPERTY;
import static org.sonar.api.CoreProperties.PROJECT_TEST_INCLUSIONS_PROPERTY;
public class AbstractExclusionFiltersTest {
@Rule
public LogTester logTester = new LogTester();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private AnalysisWarnings analysisWarnings;
private Path moduleBaseDir;
private MapSettings settings;
@Before
public void setUp() throws IOException {
settings = new MapSettings();
moduleBaseDir = temp.newFolder().toPath();
this.analysisWarnings = mock(AnalysisWarnings.class);
}
@Test
public void should_handleAliasForTestInclusionsProperty() {
settings.setProperty(PROJECT_TESTS_INCLUSIONS_PROPERTY, "**/*Dao.java");
AbstractExclusionFilters filter = new AbstractExclusionFilters(analysisWarnings, settings.asConfig()::getStringArray) {
};
IndexedFile indexedFile = new DefaultIndexedFile("foo", moduleBaseDir, "test/main/java/com/mycompany/FooDao.java", null);
assertThat(filter.isIncluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isTrue();
indexedFile = new DefaultIndexedFile("foo", moduleBaseDir, "test/main/java/com/mycompany/Foo.java", null);
assertThat(filter.isIncluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isFalse();
String expectedWarn = "Use of sonar.tests.inclusions detected. " +
"While being taken into account, the only supported property is sonar.test.inclusions. Consider updating your configuration.";
assertThat(logTester.logs(Level.WARN)).hasSize(1)
.contains(expectedWarn);
verify(analysisWarnings).addUnique(expectedWarn);
}
@Test
public void should_handleAliasForTestExclusionsProperty() {
settings.setProperty(PROJECT_TESTS_EXCLUSIONS_PROPERTY, "**/*Dao.java");
AbstractExclusionFilters filter = new AbstractExclusionFilters(analysisWarnings, settings.asConfig()::getStringArray) {
};
IndexedFile indexedFile = new DefaultIndexedFile("foo", moduleBaseDir, "test/main/java/com/mycompany/FooDao.java", null);
assertThat(filter.isExcluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isTrue();
indexedFile = new DefaultIndexedFile("foo", moduleBaseDir, "test/main/java/com/mycompany/Foo.java", null);
assertThat(filter.isExcluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isFalse();
String expectedWarn = "Use of sonar.tests.exclusions detected. " +
"While being taken into account, the only supported property is sonar.test.exclusions. Consider updating your configuration.";
assertThat(logTester.logs(Level.WARN)).hasSize(1)
.contains(expectedWarn);
verify(analysisWarnings).addUnique(expectedWarn);
}
@Test
public void should_keepLegacyValue_when_legacyAndAliasPropertiesAreUsedForTestInclusions() {
settings.setProperty(PROJECT_TESTS_INCLUSIONS_PROPERTY, "**/*Dao.java");
settings.setProperty(PROJECT_TEST_INCLUSIONS_PROPERTY, "**/*Dto.java");
AbstractExclusionFilters filter = new AbstractExclusionFilters(analysisWarnings, settings.asConfig()::getStringArray) {
};
IndexedFile indexedFile = new DefaultIndexedFile("foo", moduleBaseDir, "test/main/java/com/mycompany/FooDao.java", null);
assertThat(filter.isIncluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isFalse();
indexedFile = new DefaultIndexedFile("foo", moduleBaseDir, "test/main/java/com/mycompany/FooDto.java", null);
assertThat(filter.isIncluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isTrue();
String expectedWarn = "Use of sonar.test.inclusions and sonar.tests.inclusions at the same time. sonar.test.inclusions is taken into account. Consider updating your configuration";
assertThat(logTester.logs(Level.WARN)).hasSize(1)
.contains(expectedWarn);
verify(analysisWarnings).addUnique(expectedWarn);
}
@Test
public void should_keepLegacyValue_when_legacyAndAliasPropertiesAreUsedForTestExclusions() {
settings.setProperty(PROJECT_TESTS_EXCLUSIONS_PROPERTY, "**/*Dao.java");
settings.setProperty(PROJECT_TEST_EXCLUSIONS_PROPERTY, "**/*Dto.java");
AbstractExclusionFilters filter = new AbstractExclusionFilters(analysisWarnings, settings.asConfig()::getStringArray) {
};
IndexedFile indexedFile = new DefaultIndexedFile("foo", moduleBaseDir, "test/main/java/com/mycompany/FooDao.java", null);
assertThat(filter.isExcluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isFalse();
indexedFile = new DefaultIndexedFile("foo", moduleBaseDir, "test/main/java/com/mycompany/FooDto.java", null);
assertThat(filter.isExcluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isTrue();
String expectedWarn = "Use of sonar.test.exclusions and sonar.tests.exclusions at the same time. sonar.test.exclusions is taken into account. Consider updating your configuration";
assertThat(logTester.logs(Level.WARN)).hasSize(1)
.contains(expectedWarn);
verify(analysisWarnings).addUnique(expectedWarn);
}
} | 6,974 | 49.543478 | 184 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/AdditionalFilePredicatesTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.filesystem;
import org.junit.Test;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import static org.assertj.core.api.Assertions.assertThat;
public class AdditionalFilePredicatesTest {
@Test
public void key() {
FilePredicate predicate = new AdditionalFilePredicates.KeyPredicate("struts:Action.java");
InputFile inputFile = new TestInputFileBuilder("struts", "Action.java").build();
assertThat(predicate.apply(inputFile)).isTrue();
inputFile = new TestInputFileBuilder("struts", "Filter.java").build();
assertThat(predicate.apply(inputFile)).isFalse();
}
}
| 1,562 | 36.214286 | 94 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/ByteCharsetDetectorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.filesystem;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.io.ByteOrderMark;
import org.junit.Before;
import org.junit.Test;
import org.sonar.scanner.scan.filesystem.CharsetValidation.Result;
import org.sonar.scanner.scan.filesystem.CharsetValidation.Validation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ByteCharsetDetectorTest {
private CharsetValidation validation;
private ByteCharsetDetector charsets;
@Before
public void setUp() {
validation = mock(CharsetValidation.class);
charsets = new ByteCharsetDetector(validation, null);
}
@Test
public void detectBOM() throws URISyntaxException, IOException {
byte[] b = ByteOrderMark.UTF_16BE.getBytes();
assertThat(charsets.detectBOM(b)).isEqualTo(ByteOrderMark.UTF_16BE);
assertThat(charsets.detectBOM(readFile("UTF-8"))).isEqualTo(ByteOrderMark.UTF_8);
assertThat(charsets.detectBOM(readFile("UTF-16BE"))).isEqualTo(ByteOrderMark.UTF_16BE);
assertThat(charsets.detectBOM(readFile("UTF-16LE"))).isEqualTo(ByteOrderMark.UTF_16LE);
assertThat(charsets.detectBOM(readFile("UTF-32BE"))).isEqualTo(ByteOrderMark.UTF_32BE);
assertThat(charsets.detectBOM(readFile("UTF-32LE"))).isEqualTo(ByteOrderMark.UTF_32LE);
}
private byte[] readFile(String fileName) throws URISyntaxException, IOException {
Path path = Paths.get(this.getClass().getClassLoader().getResource("org/sonar/scanner/scan/filesystem/" + fileName + ".txt").toURI());
return Files.readAllBytes(path);
}
@Test
public void tryUTF8First() {
when(validation.isUTF8(any(byte[].class), anyBoolean())).thenReturn(Result.newValid(StandardCharsets.UTF_8));
assertThat(charsets.detect(new byte[1])).isEqualTo(StandardCharsets.UTF_8);
}
@Test
public void tryUTF16heuristics() {
when(validation.isUTF8(any(byte[].class), anyBoolean())).thenReturn(Result.INVALID);
when(validation.isUTF16(any(byte[].class), anyBoolean())).thenReturn(Result.newValid(StandardCharsets.UTF_16));
when(validation.isValidUTF16(any(byte[].class), anyBoolean())).thenReturn(true);
assertThat(charsets.detect(new byte[1])).isEqualTo(StandardCharsets.UTF_16);
}
@Test
public void failAll() {
when(validation.isUTF8(any(byte[].class), anyBoolean())).thenReturn(Result.INVALID);
when(validation.isUTF16(any(byte[].class), anyBoolean())).thenReturn(new Result(Validation.MAYBE, null));
when(validation.isValidWindows1252(any(byte[].class))).thenReturn(Result.INVALID);
assertThat(charsets.detect(new byte[1])).isNull();
}
@Test
public void failAnsii() {
when(validation.isUTF8(any(byte[].class), anyBoolean())).thenReturn(new Result(Validation.MAYBE, null));
when(validation.isUTF16(any(byte[].class), anyBoolean())).thenReturn(Result.newValid(StandardCharsets.UTF_16));
when(validation.isValidUTF16(any(byte[].class), anyBoolean())).thenReturn(true);
assertThat(charsets.detect(new byte[1])).isNull();
}
@Test
public void tryUserAnsii() {
when(validation.isUTF8(any(byte[].class), anyBoolean())).thenReturn(new Result(Validation.MAYBE, null));
when(validation.isUTF16(any(byte[].class), anyBoolean())).thenReturn(Result.newValid(StandardCharsets.UTF_16));
when(validation.isValidUTF16(any(byte[].class), anyBoolean())).thenReturn(true);
when(validation.tryDecode(any(byte[].class), eq(StandardCharsets.ISO_8859_1))).thenReturn(true);
charsets = new ByteCharsetDetector(validation, StandardCharsets.ISO_8859_1);
assertThat(charsets.detect(new byte[1])).isEqualTo(StandardCharsets.ISO_8859_1);
}
@Test
public void tryOtherUserCharset() {
when(validation.isUTF8(any(byte[].class), anyBoolean())).thenReturn(Result.INVALID);
when(validation.isUTF16(any(byte[].class), anyBoolean())).thenReturn(new Result(Validation.MAYBE, null));
when(validation.tryDecode(any(byte[].class), eq(StandardCharsets.ISO_8859_1))).thenReturn(true);
charsets = new ByteCharsetDetector(validation, StandardCharsets.ISO_8859_1);
assertThat(charsets.detect(new byte[1])).isEqualTo(StandardCharsets.ISO_8859_1);
}
@Test
public void invalidBOM() {
byte[] b1 = {(byte) 0xFF, (byte) 0xFF};
assertThat(charsets.detectBOM(b1)).isNull();
// not enough bytes
byte[] b2 = {(byte) 0xFE};
assertThat(charsets.detectBOM(b2)).isNull();
// empty
byte[] b3 = new byte[0];
assertThat(charsets.detectBOM(b3)).isNull();
}
@Test
public void windows1252() throws IOException, URISyntaxException {
ByteCharsetDetector detector = new ByteCharsetDetector(new CharsetValidation(), StandardCharsets.UTF_8);
assertThat(detector.detect(readFile("windows-1252"))).isEqualTo(Charset.forName("Windows-1252"));
}
}
| 6,031 | 41.181818 | 138 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/CharsetDetectorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.filesystem;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Random;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_16;
import static java.nio.charset.StandardCharsets.UTF_16BE;
import static java.nio.charset.StandardCharsets.UTF_16LE;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class CharsetDetectorTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void should_detect_charset_from_BOM() {
Path basedir = Paths.get("src/test/resources/org/sonar/scanner/scan/filesystem/");
assertThat(detectCharset(basedir.resolve("without_BOM.txt"), US_ASCII)).isEqualTo(US_ASCII);
assertThat(detectCharset(basedir.resolve("UTF-8.txt"), US_ASCII)).isEqualTo(UTF_8);
assertThat(detectCharset(basedir.resolve("UTF-16BE.txt"), US_ASCII)).isEqualTo(UTF_16BE);
assertThat(detectCharset(basedir.resolve("UTF-16LE.txt"), US_ASCII)).isEqualTo(UTF_16LE);
assertThat(detectCharset(basedir.resolve("UTF-32BE.txt"), US_ASCII)).isEqualTo(MetadataGenerator.UTF_32BE);
assertThat(detectCharset(basedir.resolve("UTF-32LE.txt"), US_ASCII)).isEqualTo(MetadataGenerator.UTF_32LE);
}
@Test
public void should_read_files_from_BOM() throws IOException {
Path basedir = Paths.get("src/test/resources/org/sonar/scanner/scan/filesystem/");
assertThat(readFile(basedir.resolve("without_BOM.txt"), US_ASCII)).isEqualTo("without BOM");
assertThat(readFile(basedir.resolve("UTF-8.txt"), US_ASCII)).isEqualTo("UTF-8");
assertThat(readFile(basedir.resolve("UTF-16BE.txt"), US_ASCII)).isEqualTo("UTF-16BE");
assertThat(readFile(basedir.resolve("UTF-16LE.txt"), US_ASCII)).isEqualTo("UTF-16LE");
assertThat(readFile(basedir.resolve("UTF-32BE.txt"), US_ASCII)).isEqualTo("UTF-32BE");
assertThat(readFile(basedir.resolve("UTF-32LE.txt"), US_ASCII)).isEqualTo("UTF-32LE");
}
@Test
public void always_try_utf8() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
// this is a valid 2 byte UTF-8.
out.write(194);
out.write(128);
Path filePath = temp.newFile().toPath();
Files.write(filePath, out.toByteArray());
assertThat(detectCharset(filePath, UTF_16)).isEqualTo(UTF_8);
}
@Test
public void fail_if_file_doesnt_exist() {
assertThatThrownBy(() -> detectCharset(Paths.get("non_existing"), UTF_8))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Unable to read file " + Paths.get("non_existing").toAbsolutePath());
}
@Test
public void no_encoding_found() throws IOException {
Path filePath = temp.newFile().toPath();
byte[] b = new byte[4096];
new Random().nextBytes(b);
// avoid accidental BOM matching
b[0] = 1;
// avoid UTF-8 / UTF-16
b[100] = 0;
b[101] = 0;
b[102] = 0;
b[103] = 0;
// invalid in win-1258
b[200] = (byte) 129;
Files.write(filePath, b);
CharsetDetector detector = new CharsetDetector(filePath, UTF_8);
assertThat(detector.run()).isFalse();
assertThat(detector.charset()).isNull();
}
private String readFile(Path file, Charset defaultEncoding) throws IOException {
CharsetDetector detector = new CharsetDetector(file, defaultEncoding);
assertThat(detector.run()).isTrue();
List<String> readLines = IOUtils.readLines(new InputStreamReader(detector.inputStream(), detector.charset()));
return StringUtils.join(readLines, "\n");
}
private Charset detectCharset(Path file, Charset defaultEncoding) {
CharsetDetector detector = new CharsetDetector(file, defaultEncoding);
assertThat(detector.run()).isTrue();
return detector.charset();
}
}
| 5,068 | 38.601563 | 114 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/CharsetValidationTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.filesystem;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
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.List;
import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.Test;
import org.sonar.scanner.scan.filesystem.CharsetValidation.Validation;
import static org.assertj.core.api.Assertions.assertThat;
public class CharsetValidationTest {
private CharsetValidation charsets;
@Before
public void setUp() {
charsets = new CharsetValidation();
}
@Test
public void testWithSourceCode() throws IOException {
Path path = Paths.get("test-resources/mediumtest/xoo/sample/xources/hello/HelloJava.xoo");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
String text = lines.stream().collect(StringBuffer::new, StringBuffer::append, StringBuffer::append).toString();
byte[] utf8 = encode(text, StandardCharsets.UTF_8);
byte[] utf16be = encode(text, StandardCharsets.UTF_16BE);
byte[] utf16le = encode(text, StandardCharsets.UTF_16LE);
assertThat(charsets.isUTF8(utf8, true).charset()).isEqualTo(StandardCharsets.UTF_8);
assertThat(charsets.isUTF16(utf16be, true).charset()).isEqualTo(StandardCharsets.UTF_16BE);
assertThat(charsets.isUTF16(utf16le, true).charset()).isEqualTo(StandardCharsets.UTF_16LE);
assertThat(charsets.isValidUTF16(utf16be, false)).isTrue();
assertThat(charsets.isValidUTF16(utf16le, true)).isTrue();
}
@Test
public void detectUTF16NewLine() throws CharacterCodingException {
// the first char will be encoded with a null on the second byte, but we should still detect it due to the new line
String text = "\uA100" + "\uA212" + "\n";
byte[] utf16be = encode(text, StandardCharsets.UTF_16BE);
byte[] utf16le = encode(text, StandardCharsets.UTF_16LE);
byte[] utf8 = encode(text, StandardCharsets.UTF_8);
byte[] utf32 = encode(text, Charset.forName("UTF-32LE"));
System.out.println(Arrays.toString(utf32));
assertThat(charsets.isUTF16(utf16le, true).charset()).isEqualTo(StandardCharsets.UTF_16LE);
assertThat(charsets.isUTF16(utf16be, true).charset()).isEqualTo(StandardCharsets.UTF_16BE);
assertThat(charsets.isUTF16(utf8, true).valid()).isEqualTo(Validation.MAYBE);
// this will have a double null, so it will be yes or no based on failOnNull
assertThat(charsets.isUTF16(utf32, true).valid()).isEqualTo(Validation.NO);
assertThat(charsets.isUTF16(utf32, false).valid()).isEqualTo(Validation.YES);
}
@Test
public void detectUTF16Ascii() throws CharacterCodingException {
String text = "some text to test";
byte[] utf16be = encode(text, StandardCharsets.UTF_16BE);
byte[] utf16le = encode(text, StandardCharsets.UTF_16LE);
byte[] utf8 = encode(text, StandardCharsets.UTF_8);
byte[] iso88591 = encode(text, StandardCharsets.ISO_8859_1);
byte[] utf32 = encode(text, Charset.forName("UTF-32LE"));
assertThat(charsets.isUTF16(utf16le, true).charset()).isEqualTo(StandardCharsets.UTF_16LE);
assertThat(charsets.isUTF16(utf16be, true).charset()).isEqualTo(StandardCharsets.UTF_16BE);
// not enough nulls -> we don't know
assertThat(charsets.isUTF16(iso88591, true).valid()).isEqualTo(Validation.MAYBE);
assertThat(charsets.isUTF16(utf8, true).valid()).isEqualTo(Validation.MAYBE);
// fail based on double nulls
assertThat(charsets.isUTF16(utf32, true).valid()).isEqualTo(Validation.NO);
}
@Test
public void validUTF8() {
// UTF8 with 3 bytes
byte[] b = hexToByte("E2 80 A6");
assertThat(charsets.isUTF8(b, true).valid()).isEqualTo(Validation.YES);
}
@Test
public void invalidUTF16() {
// UTF-16 will accept anything in direct 2 byte block unless it's between D800-DFFF (high and low surrogates).
// In that case, it's a 4 byte encoding it's not a direct encoding.
byte[] b1 = hexToByte("D800 0000");
assertThat(charsets.isValidUTF16(b1)).isFalse();
byte[] b1le = hexToByte("0000 D800");
assertThat(charsets.isValidUTF16(b1le, true)).isFalse();
// not enough bytes (any byte following this one would make it valid)
byte[] b2 = {(byte) 0x01};
assertThat(charsets.isValidUTF16(b2)).isFalse();
// we reject double 0
byte[] b3 = {(byte) 0, (byte) 0};
assertThat(charsets.isValidUTF16(b3)).isFalse();
}
@Test
public void invalidUTF8() {
// never expects to see 0xFF or 0xC0..
byte[] b1 = {(byte) 0xFF};
assertThat(charsets.isUTF8(b1, true).valid()).isEqualTo(Validation.NO);
byte[] b1c = {(byte) 0xC0};
assertThat(charsets.isUTF8(b1c, true).valid()).isEqualTo(Validation.NO);
// the first byte indicates a 2-byte encoding, but second byte is not valid
byte[] b2 = {(byte) 0b11000010, (byte) 0b11000000};
assertThat(charsets.isUTF8(b2, true).valid()).isEqualTo(Validation.NO);
// we reject nulls (mainly to reject UTF-16)
byte[] b3 = {(byte) 0};
assertThat(charsets.isUTF8(b3, true).valid()).isEqualTo(Validation.NO);
}
@Test
public void windows_1252() {
assertThat(charsets.isValidWindows1252(new byte[]{(byte) 129}).valid()).isEqualTo(Validation.NO);
assertThat(charsets.isValidWindows1252(new byte[]{(byte) 141}).valid()).isEqualTo(Validation.NO);
assertThat(charsets.isValidWindows1252(new byte[]{(byte) 143}).valid()).isEqualTo(Validation.NO);
assertThat(charsets.isValidWindows1252(new byte[]{(byte) 144}).valid()).isEqualTo(Validation.NO);
assertThat(charsets.isValidWindows1252(new byte[]{(byte) 157}).valid()).isEqualTo(Validation.NO);
assertThat(charsets.isValidWindows1252(new byte[]{(byte) 189}).valid()).isEqualTo(Validation.MAYBE);
assertThat(charsets.isUTF8(new byte[]{(byte) 189}, true).valid()).isEqualTo(Validation.NO);
}
@Test
public void dontFailIfNotEnoughBytes() {
byte[] b1 = hexToByte("D800");
assertThat(charsets.isValidUTF16(b1)).isTrue();
// the first byte indicates a 2-byte encoding, but there is no second byte
byte[] b2 = {(byte) 0b11000010};
assertThat(charsets.isUTF8(b2, true).valid()).isEqualTo(Validation.MAYBE);
}
private byte[] encode(String txt, Charset charset) throws CharacterCodingException {
CharsetEncoder encoder = charset.newEncoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
ByteBuffer encoded = encoder.encode(CharBuffer.wrap(txt));
byte[] b = new byte[encoded.remaining()];
encoded.get(b);
return b;
}
private static byte[] hexToByte(String str) {
String s = StringUtils.deleteWhitespace(str);
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
}
| 8,021 | 40.564767 | 119 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/InputComponentStoreTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.filesystem;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.Nullable;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Status;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.InputPath;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import static java.util.Optional.ofNullable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class InputComponentStoreTest {
private final SonarRuntime sonarRuntime = mock(SonarRuntime.class);
@ClassRule
public static TemporaryFolder temp = new TemporaryFolder();
@Test
public void should_add_input_file() throws Exception {
String rootModuleKey = "struts";
String subModuleKey = "struts-core";
File rootBaseDir = temp.newFolder();
ProjectDefinition moduleDef = ProjectDefinition.create()
.setKey(subModuleKey).setBaseDir(rootBaseDir).setWorkDir(temp.newFolder());
ProjectDefinition rootDef = ProjectDefinition.create()
.setKey(rootModuleKey).setBaseDir(rootBaseDir).setWorkDir(temp.newFolder()).addSubProject(moduleDef);
DefaultInputProject rootProject = TestInputFileBuilder.newDefaultInputProject(rootDef);
DefaultInputModule subModule = TestInputFileBuilder.newDefaultInputModule(moduleDef);
InputComponentStore store = new InputComponentStore(mock(BranchConfiguration.class), sonarRuntime);
store.put(subModule);
DefaultInputFile fooFile = new TestInputFileBuilder(rootModuleKey, "src/main/java/Foo.java")
.setModuleBaseDir(rootBaseDir.toPath())
.setPublish(true)
.build();
store.put(rootProject.key(), fooFile);
store.put(subModuleKey, new TestInputFileBuilder(rootModuleKey, "src/main/java/Bar.java")
.setLanguage("bla")
.setPublish(false)
.setType(Type.MAIN)
.setStatus(Status.ADDED)
.setLines(2)
.setCharset(StandardCharsets.UTF_8)
.setModuleBaseDir(temp.newFolder().toPath())
.build());
DefaultInputFile loadedFile = (DefaultInputFile) store.getFile(subModuleKey, "src/main/java/Bar.java");
assertThat(loadedFile.relativePath()).isEqualTo("src/main/java/Bar.java");
assertThat(loadedFile.charset()).isEqualTo(StandardCharsets.UTF_8);
assertThat(store.filesByModule(rootModuleKey)).hasSize(1);
assertThat(store.filesByModule(subModuleKey)).hasSize(1);
assertThat(store.inputFiles()).hasSize(2);
for (InputPath inputPath : store.inputFiles()) {
assertThat(inputPath.relativePath()).startsWith("src/main/java/");
}
List<InputFile> toPublish = new LinkedList<>();
store.allFilesToPublish().forEach(toPublish::add);
assertThat(toPublish).containsExactly(fooFile);
}
static class InputComponentStoreTester extends InputComponentStore {
InputComponentStoreTester(SonarRuntime sonarRuntime) {
super(mock(BranchConfiguration.class), sonarRuntime);
}
InputFile addFile(String moduleKey, String relpath, @Nullable String language) {
TestInputFileBuilder fileBuilder = new TestInputFileBuilder(moduleKey, relpath);
ofNullable(language).ifPresent(fileBuilder::setLanguage);
DefaultInputFile file = fileBuilder.build();
put(moduleKey, file);
return file;
}
InputFile addFile(String moduleKey, String relPath) {
DefaultInputFile file = new TestInputFileBuilder(moduleKey, relPath)
.build();
put(moduleKey, file);
return file;
}
}
@Test
public void should_add_languages_per_module_and_globally() {
InputComponentStoreTester tester = new InputComponentStoreTester(sonarRuntime);
String mod1Key = "mod1";
tester.addFile(mod1Key, "src/main/java/Foo.java", "java");
String mod2Key = "mod2";
tester.addFile(mod2Key, "src/main/groovy/Foo.groovy", "groovy");
assertThat(tester.languages(mod1Key)).containsExactly("java");
assertThat(tester.languages(mod2Key)).containsExactly("groovy");
assertThat(tester.languages()).containsExactlyInAnyOrder("java", "groovy");
}
@Test
public void should_find_files_per_module_and_globally() {
InputComponentStoreTester tester = new InputComponentStoreTester(sonarRuntime);
String mod1Key = "mod1";
InputFile mod1File = tester.addFile(mod1Key, "src/main/java/Foo.java", "java");
String mod2Key = "mod2";
InputFile mod2File = tester.addFile(mod2Key, "src/main/groovy/Foo.groovy", "groovy");
assertThat(tester.filesByModule(mod1Key)).containsExactly(mod1File);
assertThat(tester.filesByModule(mod2Key)).containsExactly(mod2File);
assertThat(tester.inputFiles()).containsExactlyInAnyOrder(mod1File, mod2File);
}
@Test
public void stores_not_analysed_c_file_count_in_sq_community_edition() {
when(sonarRuntime.getEdition()).thenReturn(SonarEdition.COMMUNITY);
InputComponentStoreTester underTest = new InputComponentStoreTester(sonarRuntime);
String mod1Key = "mod1";
underTest.addFile(mod1Key, "src/main/java/Foo.java", "java");
underTest.addFile(mod1Key, "src/main/c/file1.c");
underTest.addFile(mod1Key, "src/main/c/file2.c");
String mod2Key = "mod2";
underTest.addFile(mod2Key, "src/main/groovy/Foo.groovy", "groovy");
underTest.addFile(mod2Key, "src/main/c/file3.c");
assertThat(underTest.getNotAnalysedFilesByLanguage()).hasSize(1);
assertThat(underTest.getNotAnalysedFilesByLanguage()).containsEntry("C", 3);
}
@Test
public void stores_not_analysed_cpp_file_count_in_sq_community_edition() {
when(sonarRuntime.getEdition()).thenReturn(SonarEdition.COMMUNITY);
InputComponentStoreTester underTest = new InputComponentStoreTester(sonarRuntime);
String mod1Key = "mod1";
underTest.addFile(mod1Key, "src/main/java/Foo.java", "java");
underTest.addFile(mod1Key, "src/main/c/file1.c");
underTest.addFile(mod1Key, "src/main/c/file2.cpp");
underTest.addFile(mod1Key, "src/main/c/file3.cxx");
underTest.addFile(mod1Key, "src/main/c/file4.c++");
underTest.addFile(mod1Key, "src/main/c/file5.cc");
underTest.addFile(mod1Key, "src/main/c/file6.CPP");
String mod2Key = "mod2";
underTest.addFile(mod2Key, "src/main/groovy/Foo.groovy", "groovy");
underTest.addFile(mod2Key, "src/main/c/file3.cpp");
assertThat(underTest.getNotAnalysedFilesByLanguage()).hasSize(2);
assertThat(underTest.getNotAnalysedFilesByLanguage()).containsEntry("C++", 6);
}
@Test
public void does_not_store_not_analysed_file_counts_in_sq_non_community_editions() {
when(sonarRuntime.getEdition()).thenReturn(SonarEdition.DEVELOPER);
InputComponentStoreTester underTest = new InputComponentStoreTester(sonarRuntime);
String mod1Key = "mod1";
underTest.addFile(mod1Key, "src/main/java/Foo.java", "java");
underTest.addFile(mod1Key, "src/main/java/file1.c");
underTest.addFile(mod1Key, "src/main/java/file2.c");
String mod2Key = "mod2";
underTest.addFile(mod2Key, "src/main/groovy/Foo.groovy", "groovy");
underTest.addFile(mod2Key, "src/main/groovy/file4.c");
assertThat(underTest.getNotAnalysedFilesByLanguage()).isEmpty();
}
}
| 8,575 | 40.631068 | 107 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/LanguageDetectionTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.filesystem;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.io.File;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.repository.language.DefaultLanguagesRepository;
import org.sonar.scanner.repository.language.LanguagesRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.spy;
@RunWith(DataProviderRunner.class)
public class LanguageDetectionTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private MapSettings settings;
@Before
public void setUp() {
settings = new MapSettings();
}
@Test
@UseDataProvider("extensionsForSanitization")
public void sanitizeExtension_shouldRemoveObsoleteCharacters(String extension) {
assertThat(LanguageDetection.sanitizeExtension(extension)).isEqualTo("cbl");
}
@DataProvider
public static Object[][] extensionsForSanitization() {
return new Object[][] {
{".cbl"},
{".CBL"},
{"CBL"},
{"cbl"},
};
}
@Test
public void detectLanguageKey_shouldDetectByFileExtension() {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("java", "java", "jav"), new MockLanguage("cobol", "cbl", "cob")));
LanguageDetection detection = new LanguageDetection(settings.asConfig(), languages);
assertThat(detectLanguageKey(detection, "Foo.java")).isEqualTo("java");
assertThat(detectLanguageKey(detection, "src/Foo.java")).isEqualTo("java");
assertThat(detectLanguageKey(detection, "Foo.JAVA")).isEqualTo("java");
assertThat(detectLanguageKey(detection, "Foo.jav")).isEqualTo("java");
assertThat(detectLanguageKey(detection, "Foo.Jav")).isEqualTo("java");
assertThat(detectLanguageKey(detection, "abc.cbl")).isEqualTo("cobol");
assertThat(detectLanguageKey(detection, "abc.CBL")).isEqualTo("cobol");
assertThat(detectLanguageKey(detection, "abc.php")).isNull();
assertThat(detectLanguageKey(detection, "abc")).isNull();
}
@Test
@UseDataProvider("filenamePatterns")
public void detectLanguageKey_shouldDetectByFileNamePattern(String fileName, String expectedLanguageKey) {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(
new MockLanguage("docker", new String[0], new String[] {"*.dockerfile", "*.Dockerfile", "Dockerfile", "Dockerfile.*"}),
new MockLanguage("terraform", new String[] {"tf"}, new String[] {".tf"}),
new MockLanguage("java", new String[0], new String[] {"**/*Test.java"})));
LanguageDetection detection = new LanguageDetection(settings.asConfig(), languages);
assertThat(detectLanguageKey(detection, fileName)).isEqualTo(expectedLanguageKey);
}
@DataProvider
public static Object[][] filenamePatterns() {
return new Object[][] {
{"Dockerfile", "docker"},
{"src/Dockerfile", "docker"},
{"my.Dockerfile", "docker"},
{"my.dockerfile", "docker"},
{"Dockerfile.old", "docker"},
{"Dockerfile.OLD", "docker"},
{"DOCKERFILE", null},
{"infra.tf", "terraform"},
{"FooTest.java", "java"},
{"FooTest.JAVA", "java"},
{"FooTEST.java", null}
};
}
@Test
public void detectLanguageKey_shouldNotFailIfNoLanguage() {
LanguageDetection detection = spy(new LanguageDetection(settings.asConfig(), new DefaultLanguagesRepository(new Languages())));
assertThat(detectLanguageKey(detection, "Foo.java")).isNull();
}
@Test
public void detectLanguageKey_shouldAllowPluginsToDeclareFileExtensionTwiceForCaseSensitivity() {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("abap", "abap", "ABAP")));
LanguageDetection detection = new LanguageDetection(settings.asConfig(), languages);
assertThat(detectLanguageKey(detection, "abc.abap")).isEqualTo("abap");
}
@Test
public void detectLanguageKey_shouldFailIfConflictingLanguageSuffix() {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("xml", "xhtml"), new MockLanguage("web", "xhtml")));
LanguageDetection detection = new LanguageDetection(settings.asConfig(), languages);
assertThatThrownBy(() -> detectLanguageKey(detection, "abc.xhtml"))
.isInstanceOf(MessageException.class)
.hasMessageContaining("Language of file 'abc.xhtml' can not be decided as the file matches patterns of both ")
.hasMessageContaining("sonar.lang.patterns.web : **/*.xhtml")
.hasMessageContaining("sonar.lang.patterns.xml : **/*.xhtml");
}
@Test
public void detectLanguageKey_shouldSolveConflictUsingFilePattern() {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("xml", "xhtml"), new MockLanguage("web", "xhtml")));
settings.setProperty("sonar.lang.patterns.xml", "xml/**");
settings.setProperty("sonar.lang.patterns.web", "web/**");
LanguageDetection detection = new LanguageDetection(settings.asConfig(), languages);
assertThat(detectLanguageKey(detection, "xml/abc.xhtml")).isEqualTo("xml");
assertThat(detectLanguageKey(detection, "web/abc.xhtml")).isEqualTo("web");
}
@Test
public void detectLanguageKey_shouldFailIfConflictingFilePattern() {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("abap", "abap"), new MockLanguage("cobol", "cobol")));
settings.setProperty("sonar.lang.patterns.abap", "*.abap,*.txt");
settings.setProperty("sonar.lang.patterns.cobol", "*.cobol,*.txt");
LanguageDetection detection = new LanguageDetection(settings.asConfig(), languages);
assertThat(detectLanguageKey(detection, "abc.abap")).isEqualTo("abap");
assertThat(detectLanguageKey(detection, "abc.cobol")).isEqualTo("cobol");
assertThatThrownBy(() -> detectLanguageKey(detection, "abc.txt"))
.hasMessageContaining("Language of file 'abc.txt' can not be decided as the file matches patterns of both ")
.hasMessageContaining("sonar.lang.patterns.abap : *.abap,*.txt")
.hasMessageContaining("sonar.lang.patterns.cobol : *.cobol,*.txt");
}
private String detectLanguageKey(LanguageDetection detection, String path) {
org.sonar.scanner.repository.language.Language language = detection.language(new File(temp.getRoot(), path).toPath(), Paths.get(path));
return language != null ? language.key() : null;
}
static class MockLanguage implements Language {
private final String key;
private final String[] extensions;
private final String[] filenamePatterns;
MockLanguage(String key, String... extensions) {
this.key = key;
this.extensions = extensions;
this.filenamePatterns = new String[0];
}
MockLanguage(String key, String[] extensions, String[] filenamePatterns) {
this.key = key;
this.extensions = extensions;
this.filenamePatterns = filenamePatterns;
}
@Override
public String getKey() {
return key;
}
@Override
public String getName() {
return key;
}
@Override
public String[] getFileSuffixes() {
return extensions;
}
@Override
public String[] filenamePatterns() {
return filenamePatterns;
}
@Override
public boolean publishAllFiles() {
return true;
}
}
}
| 8,694 | 38.703196 | 164 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.filesystem;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.FileMetadata;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.PathUtils;
import org.sonar.scanner.issue.ignore.IgnoreIssuesFilter;
import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer;
import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader;
import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MetadataGeneratorTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private StatusDetection statusDetection = mock(StatusDetection.class);
private MetadataGenerator generator;
@Before
public void setUp() {
FileMetadata metadata = new FileMetadata(mock(AnalysisWarnings.class));
IssueExclusionsLoader issueExclusionsLoader = new IssueExclusionsLoader(mock(IssueExclusionPatternInitializer.class), mock(IgnoreIssuesFilter.class),
mock(AnalysisWarnings.class));
generator = new MetadataGenerator(statusDetection, metadata, issueExclusionsLoader);
}
@Test
public void should_detect_charset_from_BOM() {
Path basedir = Paths.get("src/test/resources/org/sonar/scanner/scan/filesystem/");
assertThat(createInputFileWithMetadata(basedir.resolve("without_BOM.txt")).charset())
.isEqualTo(StandardCharsets.US_ASCII);
assertThat(createInputFileWithMetadata(basedir.resolve("UTF-8.txt")).charset())
.isEqualTo(StandardCharsets.UTF_8);
assertThat(createInputFileWithMetadata(basedir.resolve("UTF-16BE.txt")).charset())
.isEqualTo(StandardCharsets.UTF_16BE);
assertThat(createInputFileWithMetadata(basedir.resolve("UTF-16LE.txt")).charset())
.isEqualTo(StandardCharsets.UTF_16LE);
assertThat(createInputFileWithMetadata(basedir.resolve("UTF-32BE.txt")).charset())
.isEqualTo(MetadataGenerator.UTF_32BE);
assertThat(createInputFileWithMetadata(basedir.resolve("UTF-32LE.txt")).charset())
.isEqualTo(MetadataGenerator.UTF_32LE);
}
private DefaultInputFile createInputFileWithMetadata(Path filePath) {
return createInputFileWithMetadata(filePath.getParent(), filePath.getFileName().toString());
}
private DefaultInputFile createInputFileWithMetadata(Path baseDir, String relativePath) {
DefaultInputFile inputFile = new TestInputFileBuilder("struts", relativePath)
.setModuleBaseDir(baseDir)
.build();
generator.setMetadata("module", inputFile, StandardCharsets.US_ASCII);
return inputFile;
}
@Test
public void start_with_bom() throws Exception {
Path tempFile = temp.newFile().toPath();
FileUtils.write(tempFile.toFile(), "\uFEFFfoo\nbar\r\nbaz", StandardCharsets.UTF_8, true);
DefaultInputFile inputFile = createInputFileWithMetadata(tempFile);
assertThat(inputFile.lines()).isEqualTo(3);
assertThat(inputFile.nonBlankLines()).isEqualTo(3);
assertThat(inputFile.md5Hash()).isEqualTo(md5Hex("foo\nbar\nbaz"));
assertThat(inputFile.originalLineStartOffsets()).containsOnly(0, 4, 9);
assertThat(inputFile.originalLineEndOffsets()).containsOnly(3, 7, 12);
}
@Test
public void use_default_charset_if_detection_fails() throws IOException {
Path tempFile = temp.newFile().toPath();
byte invalidWindows1252 = (byte) 129;
byte[] b = {(byte) 0xDF, (byte) 0xFF, (byte) 0xFF, invalidWindows1252};
FileUtils.writeByteArrayToFile(tempFile.toFile(), b);
DefaultInputFile inputFile = createInputFileWithMetadata(tempFile);
assertThat(inputFile.charset()).isEqualTo(StandardCharsets.US_ASCII);
}
@Test
public void non_existing_file_should_throw_exception() {
try {
createInputFileWithMetadata(Paths.get(""), "non_existing");
Assert.fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).endsWith("Unable to read file " + Paths.get("").resolve("non_existing").toAbsolutePath());
assertThat(e.getCause()).isInstanceOf(IllegalStateException.class);
}
}
@Test
public void complete_input_file() throws Exception {
// file system
Path baseDir = temp.newFolder().toPath().toRealPath(LinkOption.NOFOLLOW_LINKS);
Path srcFile = baseDir.resolve("src/main/java/foo/Bar.java");
FileUtils.touch(srcFile.toFile());
FileUtils.write(srcFile.toFile(), "single line");
// status
DefaultInputFile inputFile = createInputFileWithMetadata(baseDir, "src/main/java/foo/Bar.java");
when(statusDetection.status("foo", inputFile, "6c1d64c0b3555892fe7273e954f6fb5a"))
.thenReturn(InputFile.Status.ADDED);
assertThat(inputFile.type()).isEqualTo(InputFile.Type.MAIN);
assertThat(inputFile.file()).isEqualTo(srcFile.toFile());
assertThat(inputFile.absolutePath()).isEqualTo(PathUtils.sanitize(srcFile.toAbsolutePath().toString()));
assertThat(inputFile.key()).isEqualTo("struts:src/main/java/foo/Bar.java");
assertThat(inputFile.relativePath()).isEqualTo("src/main/java/foo/Bar.java");
assertThat(inputFile.lines()).isOne();
}
}
| 6,478 | 42.483221 | 153 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/ModuleInputComponentStoreTest.java | /*
* SonarQube
* Copyright (C) 2009-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.scanner.scan.filesystem;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.batch.fs.internal.SensorStrategy;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ModuleInputComponentStoreTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private InputComponentStore componentStore;
private final String projectKey = "dummy key";
@Before
public void setUp() throws IOException {
DefaultInputProject root = TestInputFileBuilder.newDefaultInputProject(projectKey, temp.newFolder());
componentStore = new InputComponentStore(mock(BranchConfiguration.class), mock(SonarRuntime.class));
}
@Test
public void should_cache_files_by_filename() {
ModuleInputComponentStore store = newModuleInputComponentStore();
String filename = "some name";
InputFile inputFile1 = new TestInputFileBuilder(projectKey, "some/path/" + filename).build();
store.doAdd(inputFile1);
InputFile inputFile2 = new TestInputFileBuilder(projectKey, "other/path/" + filename).build();
store.doAdd(inputFile2);
InputFile dummyInputFile = new TestInputFileBuilder(projectKey, "some/path/Dummy.java").build();
store.doAdd(dummyInputFile);
assertThat(store.getFilesByName(filename)).containsExactlyInAnyOrder(inputFile1, inputFile2);
}
@Test
public void should_cache_files_by_extension() {
ModuleInputComponentStore store = newModuleInputComponentStore();
InputFile inputFile1 = new TestInputFileBuilder(projectKey, "some/path/Program.java").build();
store.doAdd(inputFile1);
InputFile inputFile2 = new TestInputFileBuilder(projectKey, "other/path/Utils.java").build();
store.doAdd(inputFile2);
InputFile dummyInputFile = new TestInputFileBuilder(projectKey, "some/path/NotJava.cpp").build();
store.doAdd(dummyInputFile);
assertThat(store.getFilesByExtension("java")).containsExactlyInAnyOrder(inputFile1, inputFile2);
}
@Test
public void should_not_cache_duplicates() {
ModuleInputComponentStore store = newModuleInputComponentStore();
String ext = "java";
String filename = "Program." + ext;
InputFile inputFile = new TestInputFileBuilder(projectKey, "some/path/" + filename).build();
store.doAdd(inputFile);
store.doAdd(inputFile);
store.doAdd(inputFile);
assertThat(store.getFilesByName(filename)).containsExactly(inputFile);
assertThat(store.getFilesByExtension(ext)).containsExactly(inputFile);
}
@Test
public void should_get_empty_iterable_on_cache_miss() {
ModuleInputComponentStore store = newModuleInputComponentStore();
String ext = "java";
String filename = "Program." + ext;
InputFile inputFile = new TestInputFileBuilder(projectKey, "some/path/" + filename).build();
store.doAdd(inputFile);
assertThat(store.getFilesByName("nonexistent")).isEmpty();
assertThat(store.getFilesByExtension("nonexistent")).isEmpty();
}
private ModuleInputComponentStore newModuleInputComponentStore() {
InputModule module = mock(InputModule.class);
when(module.key()).thenReturn("moduleKey");
return new ModuleInputComponentStore(module, componentStore, mock(SensorStrategy.class));
}
@Test
public void should_find_module_components_with_non_global_strategy() {
InputComponentStore inputComponentStore = mock(InputComponentStore.class);
SensorStrategy strategy = new SensorStrategy();
InputModule module = mock(InputModule.class);
when(module.key()).thenReturn("foo");
ModuleInputComponentStore store = new ModuleInputComponentStore(module, inputComponentStore, strategy);
strategy.setGlobal(false);
store.inputFiles();
verify(inputComponentStore).filesByModule("foo");
String relativePath = "somepath";
store.inputFile(relativePath);
verify(inputComponentStore).getFile(any(String.class), eq(relativePath));
store.languages();
verify(inputComponentStore).languages(any(String.class));
}
@Test
public void should_find_all_components_with_global_strategy() {
InputComponentStore inputComponentStore = mock(InputComponentStore.class);
SensorStrategy strategy = new SensorStrategy();
ModuleInputComponentStore store = new ModuleInputComponentStore(mock(InputModule.class), inputComponentStore, strategy);
strategy.setGlobal(true);
store.inputFiles();
verify(inputComponentStore).inputFiles();
String relativePath = "somepath";
store.inputFile(relativePath);
verify(inputComponentStore).inputFile(relativePath);
store.languages();
verify(inputComponentStore).languages();
}
}
| 6,078 | 36.294479 | 124 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.