Skip to content

Commit

Permalink
[NO JIRA] Improve test code quality (#4824)
Browse files Browse the repository at this point in the history
Fix quality gate after more rules enabled on test code
  • Loading branch information
leonardo-pilastri-sonarsource authored Jun 20, 2024
1 parent f157787 commit a53ee33
Show file tree
Hide file tree
Showing 34 changed files with 160 additions and 169 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.junit.rules.TemporaryFolder;
import org.sonarqube.ws.Components;
import org.sonarqube.ws.Issues.Issue;

import static com.sonar.it.java.suite.JavaTestSuite.getComponent;
import static com.sonar.it.java.suite.JavaTestSuite.getMeasureAsInteger;
import static org.assertj.core.api.Assertions.assertThat;
Expand Down Expand Up @@ -152,12 +153,12 @@ public void support_change_of_extension_property() {

@Test
public void should_execute_rule_on_test() throws Exception {
MavenLocation junit_4_11 = MavenLocation.of("junit", "junit", "4.11");
orchestrator.getConfiguration().locators().copyToDirectory(junit_4_11, tmp.getRoot());
MavenLocation junit411 = MavenLocation.of("junit", "junit", "4.11");
orchestrator.getConfiguration().locators().copyToDirectory(junit411, tmp.getRoot());
MavenBuild build = MavenBuild.create()
.setPom(TestUtils.projectPom("java-inner-classes"))
.setProperty("sonar.java.test.binaries", "target/test-classes")
.setProperty("sonar.java.test.libraries", new File(tmp.getRoot(), junit_4_11.getFilename()).getAbsolutePath())
.setProperty("sonar.java.test.libraries", new File(tmp.getRoot(), junit411.getFilename()).getAbsolutePath())
.setCleanPackageSonarGoals();
TestUtils.provisionProject(orchestrator, "org.sonarsource.it.projects:java-inner-classes", "java-inner-classes", "java", "ignored-test-check");
orchestrator.executeBuild(build);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ public void unit_test_metrics() {
public void complexity_metrics() {
assertThat(getMeasureAsInteger(PROJECT_STRUTS, "complexity")).isEqualTo(5589);

int expected_statements = 12103;
expected_statements += 3; // empty statements in type declaration or member of classes in struts-1.3.9
assertThat(getMeasureAsInteger(PROJECT_STRUTS, "statements")).isEqualTo(expected_statements);
int expectedStatements = 12103;
expectedStatements += 3; // empty statements in type declaration or member of classes in struts-1.3.9
assertThat(getMeasureAsInteger(PROJECT_STRUTS, "statements")).isEqualTo(expectedStatements);
}

private static String componentKey(String path, String file) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ static WsClient newAdminWsClient(Orchestrator orchestrator) {
.build());
}

public static void provisionProject(Orchestrator ORCHESTRATOR, String projectKey, String projectName, String languageKey, String profileName) {
Server server = ORCHESTRATOR.getServer();
public static void provisionProject(Orchestrator orchestrator, String projectKey, String projectName, String languageKey, String profileName) {
Server server = orchestrator.getServer();
server.provisionProject(projectKey, projectName);
server.associateProjectToQualityProfile(projectKey, languageKey, profileName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public class JavaRulingTest {
);

@ClassRule
public static TemporaryFolder TMP_DUMP_OLD_FOLDER = new TemporaryFolder();
public static TemporaryFolder tmpDumpOldFolder = new TemporaryFolder();

private static Path effectiveDumpOldFolder;

Expand Down Expand Up @@ -159,7 +159,7 @@ private static void prepareDumpOldFolder() throws Exception {
if (SUBSET_OF_ENABLED_RULES.isEmpty()) {
effectiveDumpOldFolder = allRulesFolder.toAbsolutePath();
} else {
effectiveDumpOldFolder = TMP_DUMP_OLD_FOLDER.getRoot().toPath().toAbsolutePath();
effectiveDumpOldFolder = tmpDumpOldFolder.getRoot().toPath().toAbsolutePath();
Files.list(allRulesFolder)
.filter(p -> p.toFile().isDirectory())
.forEach(srcProjectDir -> copyDumpSubset(srcProjectDir, effectiveDumpOldFolder.resolve(srcProjectDir.getFileName())));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public void scanFile(JavaFileScannerContext context) {
}

@Rule(key = "NoEffectCheck")
protected final static class NoEffectCheck implements JavaFileScanner {
protected static final class NoEffectCheck implements JavaFileScanner {

@Override
public void scanFile(JavaFileScannerContext context) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import org.sonar.java.checks.verifier.CheckVerifier;

import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath;
import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath;;
import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath;

class ForLoopIncrementAndUpdateCheckTest {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@

class SubClassStaticReferenceCheckTest {

private static final String filename = mainCodeSourcesPath("checks/SubClassStaticReferenceCheckSample.java");
private static final String FILENAME = mainCodeSourcesPath("checks/SubClassStaticReferenceCheckSample.java");

@Test
void detected() {
CheckVerifier.newVerifier()
.onFile(filename)
.onFile(FILENAME)
.withCheck(new SubClassStaticReferenceCheck())
.verifyIssues();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@

class BrainMethodCheckTest {

private static final String highComplexityFilePath = mainCodeSourcesPath("checks/BrainMethodCheckSample.java");
private static final String lowComplexityFilePath = mainCodeSourcesPath("checks/BrainMethodCheckLowerThresholds.java");
private static final String subsetFilePath = mainCodeSourcesPath("checks/BrainMethodCheckSubsetOfIssues.java");
private static final String HIGH_COMPLEXITY_FILE_PATH = mainCodeSourcesPath("checks/BrainMethodCheckSample.java");
private static final String LOW_COMPLEXITY_FILE_PATH = mainCodeSourcesPath("checks/BrainMethodCheckLowerThresholds.java");
private static final String SUBSET_FILE_PATH = mainCodeSourcesPath("checks/BrainMethodCheckSubsetOfIssues.java");

@Test
void testHighComplexityFileWithDefaultThresholds() {
CheckVerifier.newVerifier()
.onFile(highComplexityFilePath)
.onFile(HIGH_COMPLEXITY_FILE_PATH)
.withChecks(new BrainMethodCheck())
.verifyIssues();
}
Expand All @@ -48,15 +48,15 @@ void testHighComplexityFileWithHigherThresholds() {
check.cyclomaticThreshold = 45;

CheckVerifier.newVerifier()
.onFile(highComplexityFilePath)
.onFile(HIGH_COMPLEXITY_FILE_PATH)
.withChecks(check)
.verifyNoIssues();
}

@Test
void testLowComplexityFileWithDefaultThresholds() {
CheckVerifier.newVerifier()
.onFile(lowComplexityFilePath)
.onFile(LOW_COMPLEXITY_FILE_PATH)
.withChecks(new BrainMethodCheck())
.verifyNoIssues();
}
Expand All @@ -70,7 +70,7 @@ void testLowComplexityFileWithLowerThresholds() {
check.cyclomaticThreshold = 5;

CheckVerifier.newVerifier()
.onFile(lowComplexityFilePath)
.onFile(LOW_COMPLEXITY_FILE_PATH)
.withChecks(check)
.verifyIssues();
}
Expand All @@ -87,7 +87,7 @@ void testSubsetOfIssuesWithLowerThresholds() {
check.numberOfIssuesToReport = 1;

CheckVerifier.newVerifier()
.onFile(subsetFilePath)
.onFile(SUBSET_FILE_PATH)
.withChecks(check)
.verifyIssues();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,16 @@
*/
package org.sonar.java.checks.helpers;

import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.cache.ReadCache;
import org.sonar.java.caching.FileHashingUtils;
import org.sonar.java.checks.verifier.internal.InternalInputFile;
import org.sonar.java.checks.verifier.internal.InternalReadCache;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collection;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.cache.ReadCache;
import org.sonar.java.caching.FileHashingUtils;
import org.sonar.java.checks.verifier.internal.InternalInputFile;
import org.sonar.java.checks.verifier.internal.InternalReadCache;

public class HashCacheTestHelper {

Expand All @@ -49,8 +48,7 @@ public static String contentHashKey(InputFile inputFile) {
public static ReadCache internalReadCacheFromFile(String path) throws NoSuchAlgorithmException, IOException {
InputFile cachedFile = inputFileFromPath(path);
byte[] cachedHash = FileHashingUtils.inputFileContentHash(cachedFile);
InternalReadCache localReadCache = new InternalReadCache().put(contentHashKey(cachedFile), cachedHash);
return localReadCache;
return new InternalReadCache().put(contentHashKey(cachedFile), cachedHash);
}

public static ReadCache internalReadCacheFromFiles(Collection<String> paths) throws NoSuchAlgorithmException, IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ void arguments_of_unknown_method() {

@Test
void wrapper_type_with_invalid_primitive() {
Type invalid_primitive = mock(Type.class);
when(invalid_primitive.isPrimitive()).thenReturn(true);
when(invalid_primitive.fullyQualifiedName()).thenReturn("invalid_name");
Type type = AssertionTypesCheck.wrapperType(invalid_primitive);
assertThat(type).isSameAs(invalid_primitive);
Type invalidPrimitive = mock(Type.class);
when(invalidPrimitive.isPrimitive()).thenReturn(true);
when(invalidPrimitive.fullyQualifiedName()).thenReturn("invalid_name");
Type type = AssertionTypesCheck.wrapperType(invalidPrimitive);
assertThat(type).isSameAs(invalidPrimitive);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,20 @@

class JUnit5DefaultPackageClassAndMethodCheckTest {

private static final String testSourcePath = testCodeSourcesPath("checks/tests/JUnit5DefaultPackageClassAndMethodCheckSample.java");
private static final String TEST_SOURCE_PATH = testCodeSourcesPath("checks/tests/JUnit5DefaultPackageClassAndMethodCheckSample.java");

@Test
void test() {
CheckVerifier.newVerifier()
.onFile(testSourcePath)
.onFile(TEST_SOURCE_PATH)
.withCheck(new JUnit5DefaultPackageClassAndMethodCheck())
.verifyIssues();
}

@Test
void test_without_semantic() {
CheckVerifier.newVerifier()
.onFile(testSourcePath)
.onFile(TEST_SOURCE_PATH)
.withCheck(new JUnit5DefaultPackageClassAndMethodCheck())
.withoutSemantic()
.verifyNoIssues();
Expand Down
17 changes: 17 additions & 0 deletions java-frontend/src/test/files/model/ExpressionUtilsTestSample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class ExpressionUtilsTestSample {

private boolean parenthesis(boolean b1, boolean b2) {
return (((b1 && (b2))));
}

private void simpleAssignment() {
int x;
x = 14;
(x) = 14;
x += 1;

int[] y = new int[5];
y[x] = 42;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ class B {
Object obj = new I() {
@Override
public void foo() {

// empty implementation
}
};
}
Expand Down
36 changes: 18 additions & 18 deletions java-frontend/src/test/java/org/sonar/java/JavaFrontendTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -735,35 +735,35 @@ void batch_generator_returns_batches_with_multiple_files_that_are_smaller_than_b
sensorContext = SensorContextTester.create(baseDir);
sensorContext.setSettings(new MapSettings());
}
InputFile A = addFile("class A { public void doSomething() {} }", sensorContext);
InputFile B = addFile("class B extends A {}", sensorContext);
InputFile C = addFile("class C {}", sensorContext);
InputFile fileA = addFile("class A { public void doSomething() {} }", sensorContext);
InputFile fileB = addFile("class B extends A {}", sensorContext);
InputFile fileC = addFile("class C {}", sensorContext);

long sizeofA = A.file().length() + 1;
long sizeofA = fileA.file().length() + 1;
JavaFrontend.BatchGenerator generator = new JavaFrontend.BatchGenerator(
Arrays.asList(A, B, C).iterator(), sizeofA
Arrays.asList(fileA, fileB, fileC).iterator(), sizeofA
);
assertThat(generator.hasNext()).isTrue();
assertThat(generator.next()).hasSize(1).contains(A);
assertThat(generator.next()).hasSize(1).contains(fileA);
assertThat(generator.hasNext()).isTrue();
List<InputFile> batchWithMultipleFiles = generator.next();
assertThat(batchWithMultipleFiles).hasSize(2).contains(B).contains(C);
assertThat(batchWithMultipleFiles).hasSize(2).contains(fileB).contains(fileC);
long batchSize = batchWithMultipleFiles.stream().map(i -> i.file().length()).reduce(0L, Long::sum);
assertThat(batchSize).isLessThanOrEqualTo(sizeofA);
assertThat(generator.hasNext()).isFalse();
assertThat(generator.next()).isEmpty();

long sizeOfAPlusB = A.file().length() + B.file().length();
long sizeOfAPlusB = fileA.file().length() + fileB.file().length();
generator = new JavaFrontend.BatchGenerator(
Arrays.asList(A, B, C).iterator(), sizeOfAPlusB
Arrays.asList(fileA, fileB, fileC).iterator(), sizeOfAPlusB
);
assertThat(generator.hasNext()).isTrue();
batchWithMultipleFiles = generator.next();
assertThat(batchWithMultipleFiles).hasSize(2).contains(A).contains(B);
assertThat(batchWithMultipleFiles).hasSize(2).contains(fileA).contains(fileB);
batchSize = batchWithMultipleFiles.stream().map(i -> i.file().length()).reduce(0L, Long::sum);
assertThat(batchSize).isLessThanOrEqualTo(sizeOfAPlusB);
assertThat(generator.hasNext()).isTrue();
assertThat(generator.next()).hasSize(1).contains(C);
assertThat(generator.next()).hasSize(1).contains(fileC);
assertThat(generator.hasNext()).isFalse();
assertThat(generator.next()).isEmpty();
}
Expand All @@ -775,18 +775,18 @@ void batch_generator_includes_file_excluded_from_previous_batch_into_next_batch(
sensorContext = SensorContextTester.create(baseDir);
sensorContext.setSettings(new MapSettings());
}
InputFile A = addFile("class A { public void doSomething() {} }", sensorContext);
InputFile B = addFile("class B extends A {}", sensorContext);
InputFile C = addFile("class C {}", sensorContext);
InputFile fileA = addFile("class A { public void doSomething() {} }", sensorContext);
InputFile fileB = addFile("class B extends A {}", sensorContext);
InputFile fileC = addFile("class C {}", sensorContext);
JavaFrontend.BatchGenerator generator = new JavaFrontend.BatchGenerator(
Arrays.asList(A, C, B).iterator(), C.file().length()
Arrays.asList(fileA, fileC, fileB).iterator(), fileC.file().length()
);
assertThat(generator.hasNext()).isTrue();
assertThat(generator.next()).hasSize(1).contains(A);
assertThat(generator.next()).hasSize(1).contains(fileA);
assertThat(generator.hasNext()).isTrue();
assertThat(generator.next()).hasSize(1).contains(C);
assertThat(generator.next()).hasSize(1).contains(fileC);
assertThat(generator.hasNext()).isTrue();
assertThat(generator.next()).hasSize(1).contains(B);
assertThat(generator.next()).hasSize(1).contains(fileB);
assertThat(generator.hasNext()).isFalse();
assertThat(generator.next()).isEmpty();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -498,15 +498,17 @@ private static class FakeAuditListener implements JavaFileScanner, ExceptionHand

@Override
public void processRecognitionException(RecognitionException e) {
// empty implementation
}

@Override
public void processException(Exception e) {
// empty implementation
}

@Override
public void scanFile(JavaFileScannerContext context) {

// empty implementation
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@
*/
package org.sonar.java.ast.visitors;

import com.google.common.io.Files;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import org.junit.Rule;
Expand Down Expand Up @@ -52,7 +50,6 @@ class SonarSymbolTableVisitorTest {

@Rule
public TemporaryFolder temp = new TemporaryFolder();
private static final String EOL = "\n";
private SensorContextTester context;
private SonarComponents sonarComponents;

Expand Down
Loading

0 comments on commit a53ee33

Please sign in to comment.